[英]Global $.ajaxSetup() call doesn't affect $.ajax() calls in separate functions?
Is there a way to make the scope of $.ajaxSetup() extend to function bodies? 有没有办法使$ .ajaxSetup()的范围扩展到函数体? I cannot get $.ajaxSetup() to affect the $.ajax() calls within functions.
我无法获得$ .ajaxSetup()来影响函数中的$ .ajax()调用。 Here's an example:
这是一个例子:
With the following code, the ajax request sent by function foo() does not include the testHeader specified in ajaxSetup: 使用以下代码,由函数foo()发送的ajax请求不包括ajaxSetup中指定的testHeader:
$.ajaxSetup({
headers: {
testHeader: testValue
}
});
function foo(theData) {
$.ajax({
url: testUrl,
data: theData,
type: 'POST',
contentType: 'application/json',
dataType: 'json'
});
}
However, with the following code, the testHeader does get included in the ajax request sent by foo(). 但是,使用以下代码,testHeader确实包含在foo()发送的ajax请求中。
function foo(theData) {
$.ajaxSetup({
headers: {
testHeader: testValue
}
});
$.ajax({
url: testUrl,
data: theData,
type: 'POST',
contentType: 'application/json',
dataType: 'json'
});
}
I thought ajaxSetup() is supposed to be global and its scope should extend to function bodies. 我以为ajaxSetup()应该是全局的,其范围应该扩展到函数体。 What am I missing?
我想念什么? Thanks.
谢谢。
"Global" may be a misnomer. “全球”可能用词不当。
$.ajaxSetup will only affect the current jQuery object. $ .ajaxSetup将仅影响当前的jQuery对象。 If you load jQuery in another page, it will not be affected.
如果您在另一个页面中加载jQuery,它将不会受到影响。
Well, I think the problem is that $.ajaxSetup() is a function call, not a variable. 好吧,我认为问题在于$ .ajaxSetup()是函数调用,而不是变量。 So when foo() is called, $.ajaxSetup() isn't called by anything yet.
因此,在调用foo()时,尚未有$ .ajaxSetup()调用。 Here's how I made it work: put $.ajaxSetup() in a $(function(){}) call:
这是我的工作方式:将$ .ajaxSetup()放入$(function(){})调用中:
$(function () {
$.ajaxSetup({
headers: {
testHeader: testValue
}
});
});
Then the ajax request in foo() will contain the testHeader as desired. 然后,foo()中的ajax请求将根据需要包含testHeader。 Not sure if this is the best solution but it works for me.
不知道这是否是最好的解决方案,但对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.