Access “data” object in AJAX request inside success function

☆樱花仙子☆ 提交于 2021-01-29 04:02:54

问题


How can I access the data object used in a $.ajax() request?

$.ajax({
    url: "post.php",
    type:'POST',
    data:{
        el1: $('#el1').val(),
        ...
        el72: $('#el72').val()
    },
    success: function(res,status){
        //
    }
});

回答1:


You can access the processed options that you passed into $.ajax from within the success callback using this, as long as you didn't bind the function, use an arrow function, or use the context option.

console.log(this.data); // for POST
console.log(this.url); // for GET, but you'll have to parse out the url portion

You'll notice though that it's in a parameterized string rather than an object now because that's how it is sent to the server. See here for ways to convert it back to an object: Convert URL parameters to a JavaScript object


I would just use a variable.




回答2:


Create a variable before calling ajax().

var formData = {
    el1: $('#el1').val(),
    ...
    el72: $('#el72').val()
};

$.ajax({
    url: "post.php",
    type:'POST',
    data: formData,
    success: function(res,status){
        // do something with formData
    }
});


来源:https://stackoverflow.com/questions/37818214/access-data-object-in-ajax-request-inside-success-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!