I searched a lot, but I could not find anything. The function below is making a database request and getting the data through $.post. I get the data in the inner function but I need it outside to equal some data to outputString variable. If you read the code you will see what I need.
function calculatePrice(checkInDate, checkOutDate, nights){
var rentDetailsArr = <?php echo json_encode($periods); ?>;
var minDays = ["<?php echo implode('","',$minDaysArr)?>"];
var outputString ="";
var stDate = "2010-02-10";
var endDate = "2010-09-29";
var xxx = $.post('testData.php',
{ opType:"getSelectedPeriodDetails", startDate: stDate, endDate: endDate },
function getData(data) {
$(data).each (function (index){
//I am able to get the data in here.but i need to equal it to outputString variable.
var price = data['period_id'][0];
//alert(price);
alert(price);
});
}, "json");
//when I equal $.post return to xxx variable, the return is as [object XMLHttpRe开发者_如何转开发quest ]
alert(xxx);
return outputString;
}
Now how I can handle the data out side?..can handle the data through xxx variable. If I can , how i will parse it? Sorry, if I have used wrong terms in explaining the problem. I am not very familiar with but I still can use.
You can set outputString inside ajax callback function like this:
$(data).each (function (index){
// set price to outputString
outputString = data['period_id'][0];
});
In $(data).each
the price
will always have the last index value. I assume you would need all index values. As @alififty answered you could hold it in outputString then make outputString an array that will keep all index values:
var outputString = [];
$(data).each (function (index){
// set price to outputString
outputString.push(data['period_id'][0]);
});
Additionally, if you want to do something with the results like:
var price = calculatePrice("xxxx", "xxxx", "xxxx").Tax();
Then you could do this by JavaScript Function Chaining
function hello() {
if(!(this instanceof hello))
return new hello();
var _hello = "Hello ";
this.world = function(message) {
alert(_hello + message);
}
}
hello().world("World!");
Asynchronous JavaScript and XML is Asynchronous.
The function you pass to post
runs when the HTTP response is received and not immediately.
You have to handle the data inside that callback function. You cannot return from it because it is too late.
精彩评论