简体   繁体   中英

jQuery ajax data post problem

I've been searching to the answer for a while, I want to be able to parametrise my plugins AJAX values. So eg rather than:

$.post('test.aspx', { name: 'bob' }, function(data){
....
});

I want to parametrise name and the value used in the post so eg

var var1 = 'name';
var var2 = 'bob';
$.post('test.aspx', { var1: var2 }, function(data){
....
});

My problem is that it inserts the value 'bob' but posts it as 'var1' rather than 'name'. And on the server side it is expecting name not var1.

Anyone got any ideas?

Try building a hash for your data and then passing it to the post function. Like so:

var data = {};
data[var1] = var2;
data[var3] = var4;

$.post('test.aspx', data, function(returnData) { blah, blah blah; }); 

This works for me:

$(document).ready(function()
{

    var var1 = "bobsname";
    var var2 = "bob";

    ajax(var1, var2)

    function ajax(name, variable)
    {
        $.ajax(
        {
            type: "POST",
            data: name + "=" + variable,
            url: "action.php",
            success: function(html)
            {
                alert(html);
            }
        });
    }
});

Im using the ajax function .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM