简体   繁体   English

在成功函数内访问AJAX请求中的“数据”对象

[英]Access “data” object in AJAX request inside success function

How can I access the data object used in a $.ajax() request? 如何访问$.ajax()请求中使用的data对象?

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

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. 您可以使用this从成功回调中访问传递给$ .ajax的已处理选项,只要您没有绑定该函数,使用箭头函数或使用上下文选项即可。

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 有关将其转换回对象的方法,请参见此处: 将URL参数转换为JavaScript对象


I would just use a variable. 我只会使用一个变量。

Create a variable before calling ajax() . 在调用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
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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