javascript / jquery - understanding jquery's post() and javascript's process() functions
I'm trying to post some data to a webservice and utilize the XML data it returns. I saw the example in JQuery's documentation for the post() function:
$.post("test.php", { name: "John", time: "2pm" },
function(data) {
p开发者_如何学Pythonrocess(data);
},
"xml"
);
What does the process function do? What does the data look like? Do I assign this processed data to a variable? Just trying to get an idea of how I would utilize the values returned from this post().
What does the process function do?
There is no such standard function. It's up to you to define it, so it will do whatever you tell it to do.
What does the data look like?
That will depend on what does your web service returns. If it is XML, it will represent a XML tree. So for example if you service returns the following xml:
<foo>
<bar>some value</bar>
</foo>
you could query the value of the bar
node like this:
function(data) {
var value = $('bar', data).text();
alert(value);
}
And here's a live demo where you can see it in action.
process(data);
can be any function that you want to call that does something with the data
. In most cases, you'd want to assign the data to an element or do some other massaging before displaying to the user.
Unless its very involved, you can skip calling a separate function too, e.g.:
$.post("test.php", { name: "John", time: "2pm" },
function(data) {
$('#target').html(data); // assuming data is a html string
},
"xml"
);
Taking it to process shape:
$.post("test.php", { name: "John", time: "2pm" },
function(data) {
process(data)
},
"xml"
);
function process(data) {
$('#target').html(data); // assuming data is a html string
}
If your data in some other format, then you'd massage it to extract relevant bits or transform it in some way inside process
or any custom function.
E.g., let's say you get a JSON object back:
data = { "status": "success", "text": "Processed Succesfully" };
then in your callback, you'd check for status and the display message appropriately
function process(data) {
if(data.status == "success")
$('#target').html(data.text); // assuming data is a html string
else
alert("Error");
}
精彩评论