How to get data from jQuery.post()?
My problem is that i wanna use post data outside it's function, example:
$(function() {
var s = 'something ';
$.post(开发者_运维知识库'ajax.php', {option: 'test'}, function(data) {
s += data; // data: 'hello world';
});
alert(s); // output: 'something ';
});
my expected result is 'something hello world'. how can i deal with this?
ThanksShouldn't that be:
$(function() {
var s = 'something ';
$.post('ajax.php', {option: 'test'}, function(data) {
s += data; // data: 'hello world';
alert(s); // output: 'something ';
});
});
Obviously, the data will be available in s
only after the ajax call has been completed (as Alex pointed out), but after that it will be persistent...
var s = 'something ';
$.ajax({
url: 'ajax.php',
type: "POST",
data: ({option: 'test'}),
async:false,
success: function(data){
s += data;
}
}
);
alert(s);
you need to synchronize the request by async:false,
Use $.ajax
with async:false
, I assume the data is coming as content-type:json/application
e.g.
var s = 'something ';
$.ajax({
url: "ajax.php",
type: "POST",
data: ({option: 'test'}),
dataType: "json",
async:false,
success: function(msg){
s += msg.data;//msg={data: "hello world"}
}
}
);
alert(s);
You have a syntax error; there should be a )
at the end of the post()
callback.
In addition, when that alert()
is called, the XHR has not finished yet and assigned the new info to that variable. You would need to place it in the callback of post()
.
You could write the data to any number of html elements and have it available outside of the function. You could use a global variable. You could store in session. Many answers here. Do I understand your question?
You code should be working. Unless the ajax.php
is not echoing "Hello World" at the end. Please make sure of it and try to post the results. Errors or output, whatever you can feed us.
精彩评论