weixin_33688840 2016-06-19 21:55 采纳率: 0%
浏览 7

简化ajax对象

I have this function to write the inputs from a form to the database and i'm trying to simplify the data being passed by the ajax call to the php. Currently i have this function:

function writeDB(stage){
    var userData = $("#cacheDB").find("input").get();
    var ajaxData = []
    for (var n=0;n < userData.length; n++){
        item = {};
        item[userData[n].id] = userData[n].value;
        ajaxData.push(item);
    }

    $.ajax({
        url: "x.php",
        data: {ajaxData},
    });
}

Which sends out this object:

http://url.php?ajaxData[0][pageid]=1&ajaxData[1][input1]=John&ajaxData[2][input2]=Doe

I would like to send only the original data key, like:

http://url.php?[pageid]=1&[input1]=John&[input2]=Doe

Or

http://url.php?pageid=1&input1=John&input2=Doe

Is it posible? I've tried several methods and havn't found one suitable yet.

  • 写回答

1条回答 默认 最新

  • weixin_33711647 2016-06-19 22:12
    关注

    I would try to serialize the form instead of that for loop. It basically sends all input fields from your form as a JSON object to the server.

    $.post('server.php', $('#theForm').serialize())
    

    For larger form, HTTP POST method should be prefferd, you can send complicated object.

    Check this for more help: jQuery AJAX submit form

    Hope its what you need.

    评论

报告相同问题?