[英]How to Get $.ajax() request parameter at success callback function?
I want get ajax data parameter at success callback function 我想在成功回调函数中获取ajax数据参数
like bellow 像波纹管
$.ajax({
url: 'example.com/something',
method: 'GET',
data: { 'sample':'test' }, // => I want this data in success function.
success: function(response, textStatus, jqXHR){
// want get data parameter
// {'sample':'test'}
// someone answered that could get below code but I couldn't get it
// console.log(this.data); => X
}
});
Should just be able to type data.sample
in the success handler to get the value. 应该能够在成功处理程序中键入data.sample
以获得值。 Alternately, you could do data['sample']
, but that syntax really exists more for allowing you to store property names in variables for retrieving data from objects. 或者,您可以执行data['sample']
,但该语法确实存在更多,可让您将属性名称存储在变量中以从对象中检索数据。
Change method
to type
and console.log(data)
to view the content of data
passed to the callback function. 更改method
的type
和console.log(data)
以查看传递给回调函数的data
的内容。
Also, add dataType: 'json'
in the call. 另外,在调用中添加dataType: 'json'
。
$.ajax({
url: 'example.com/something',
type: 'GET',
dataType: 'json',
data: { 'sample':'test' },
success: function(data, textStatus, jqXHR){
console.log(data); // will display the content of data
},
error: function(a,b,c) {
console.log('something went wrong:',a,b,c);
}
});
Instead of this.data
, in your case, to access the value "test", you'd need to use data.sample
. 在您的情况下,您需要使用data.sample
而不是this.data
来访问值“ test”。
Try looking into JSON objects, as that is generally what AJAX requests will be returning. 尝试查看JSON对象,因为通常这将返回AJAX请求。 You're going to using "dot notation" a lot in JS. 您将在JS中大量使用“点符号”。
What's your backend code? 你的后端代码是什么? java c# php? Java的C#的PHP? if c# and mvc controller,you can defination an action the pramater in the action will be you ajax pass 如果使用c#和mvc控制器,则可以定义一个动作,该动作中的pramater将是ajax传递
// want get data parameter // {'sample':'test'}
Pass data
as a property to jqxhr
object at beforeSend
, get object at success
. 通过data
作为属性jqxhr
在对象beforeSend
,在获得对象success
。
$.ajax({
url: 'example.com/something',
method: 'GET',
data: {
"sample": "test"
},
beforeSend: function(jqxhr, settings) {
jqxhr._data = settings.url.split("?").pop();
},
success: function(data, textStatus, jqXHR) {
// want get data parameter
// {'sample':'test'}
var _data = jqXHR._data.split("&").slice(0, 1).pop().split("=");
var obj = {}; obj[_data[0]] = _data[1];
console.log(_data, obj);
// var obj = {};
// someone answered that could get below code but I couldn't get it
// console.log(this.data); => X
}
})
Other solution, you can put data into variable directly : 其他解决方案,您可以将数据直接放入变量中:
var dataObj = {
sample:'test'
}; // => I want this data in success function.
$.ajax({
url: 'example.com/something',
method: 'GET',
data: dataObj,
success: function(response, textStatus, jqXHR){
// then just console.log(dataObj.sample)
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.