开发者

How to use dynamic data name with jQuery.post?

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

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

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

Here's my code :

$('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;
});     

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].

开发者_开发知识库Is there a way to have a dynamic a?


Try this:

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

So like this:

$('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());
    });
});


Yes, use something else for the data post:

$.post(url, a+"="+b,function(data) {
    $(data).find('string').each(function(){
        $('.result').html($(this).text());
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜