如何在jQuery.post中使用动态数据名称? [英] How to use dynamic data name with jQuery.post?

查看:179
本文介绍了如何在jQuery.post中使用动态数据名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2种用于转换数据的基本形式(类型1<->类型2).

I have 2 basic form used to convert data (type 1 <-> type 2).

我只想使用1种形式来提交我的.post请求.

I want to do my .post request using only 1 form.

jquery.post的[data]参数出现问题

I'm having issue with the [data] parameter for jquery.post

这是我的代码:

$('form').submit(function(){
    var a = $(this).parent().find("input").attr('name');
    var b = $(this).parent().find("input").val();
    var url = $(this).attr('action')
    $.post(url, { a:b },function(data) {
        $(data).find('string').each(function(){
            $('.result').html($(this).text());
        });
    });
    return false;
});     

问题出在{a:b}之内. b被解释为我的var b,但不是a,这使我的发布参数类似于[a:1]而不是[param:1].

The problem lies within {a:b}. b is interpreted as my var b, but a isn't, making my post parameters something like [a:1] instead of [param:1].

有没有办法动态制作a?

推荐答案

尝试一下:

var data = {};
data[a] = b;
$.post(url, data, function(data) {

像这样:

$('form').on('submit', function (e) {
    e.preventDefault();

    var data = {};
    var el = $(this);
    var input = el.parent().find('input');

    var a = input.attr('name');
    var b = input.val();
    var url = el.attr('action');

    data[a] = b;

    $.post(url, data, function(data) {
        $(data).find('string').each(function(){
        $('.result').html($(this).text());
    });
});

这篇关于如何在jQuery.post中使用动态数据名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆