When I write a function in JSON, why do I have to enclose it inside an anonymous function?
This works:
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: function(data) {
alert(data);
}
});
This doesn't work:
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: alert(data)
});
Thanks
You can do that. You just using the wrong syntax
.
The success
property needs a function expression not a function() call (which then returns a value into success
);
So
success: myfunction
instead of
success: myfunction()
In short, because you're executing alert()
and trying to assign the result to the success
callback, so this won't work (the result of alert()
is undefined
). However you can do this:
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: customFunc //*not* customFunc() which would call it
});
In this case customFunc
will receive the same parameters as success
passes, so it's signature should be: customFunc(data, textStatus, XMLHttpRequest)
, though it can be a subset, for example customFunc(data)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.