How to execute jQuery callback before data?
I have a simple post, which executed the data returned as a script as such:
$.post("/home"开发者_开发百科, { foo: 'bar' }, function(){
//callback function
}, "script");
Here's what happens:
- The request gets sent
- A piece of JS code is returned as a response and executed
- The callback is executed
I need the callback to be executed before the returned JS is executed. Is there a way to achieve this?
Thanks!
You can't change how jQuery handle the request. After all, a callback is a callback and it gets executed once the job is done! You can, however, set the dataType
to "text"
and then eval your Javascript.
Ex:
$.post("/home", { foo: 'bar' }, function(data){
//callback function
// execute JS
$.globalEval( data );
}, "text");
** UPDATE **
This is what jQuery does internally (snipped) :
// If the type is "script", eval it in global context
} else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
jQuery.globalEval( data );
}
So, there is no security risk with taking the globalEval
out of the Ajax request and executing it in the callback function.
Use $.ajax()
and build your own script tag.
$.ajax({url:"/home",
data: { foo: 'bar' },
type: "POST",
dataType: 'text', // Return dataType is "text" instead of "script"
success: function( script ){
// run your code
alert('mycode');
// then create your own script tag
var tag = document.createElement('script');
tag.setAttribute('type','text/javascript');
tag.appendChild(document.createTextNode(script));
document.getElementsByTagName('head')[0].appendChild(tag);
}
});
You could use "BeforeSend" option that is executed before send the ajax request:
$.ajax({
type: "POST",
url: "SOMEURL",
data: { "WHATEVER": whatever },
beforeSend: function() {
//DO WHATEVER BEFORE SEND AJAX CALL
}
.....
});
}
Hope this helps.
best regards.
Jose
This $.post() function does not automatically execute the JS which is returned. It is probably executed in the callback function.
精彩评论