Is it possible to return two different data on success in ajax, for example:
$.a开发者_JAVA技巧jax({
url: url_action,
type:'POST',
data: dataToSend,
success:function(results)
{
$(".photosLive").html(results);
}
});
In results, there are two pieces of information: Title and Image.
Then I need to put title in another div .titleLive
and put image in .photosLive
(but it's already OK)
How can I do this?
You could return a JSON object containing two fields, title and photo which you can then parse and insert into your DOM
JSON syntax is basically Javascript object syntax, take a look at:
http://www.json.org/js.html
There are JSON generators from Objects for almost any server side language
JSON example: Say your server generates the string I assigned to the var json (instead of html) so you receive it as response of your ajax call into your success method
var json = '{title:"A new title", photo:"path/to/pic"}'
var result = jQuery.parseJSON( json );
$('.titleLive').text(result.title);
$('.photosLive').attribute(src, result.photo);
To return your response in JSON is just plain text with correct format, for example in your server side something like:
setResponse("{title:\"A new title\", photo:\"path/to/pic\"}");
Well. The best way to do this is to have whatever URL you're requesting return the result as JSON. If, however, it has to return HTML, you could do this:
...
success: function(results) {
// select the image and title from wherever it may be in the HTML returned
var response = $(results),
title = response.find('#title').text(),
image = response.find('img').attr('src');
// Do whatever with your info.
}
Edit: Example with JSON return:
The page returning the title and image information:
{"title":"My Title","image":"http://mydomain.com/image.png"}
And your success callback (you don't have to set new variables for the response, I'm just doing it to illustrate):
success: function(results) {
var title = results.title,
image = results.image;
// Do whatever with your info.
}
It all depend on the data type you return (Json/XML/etc.).
Suppose you return plain text: title:lorup ipsum,image:foobar.png
:
In the success
function:
var returnedData = results;
var title = returnedData.split(",")[0].replace('title:','');
var image= returnedData.split(",")[1].replace('image:','');
$(".titleLive").html(title );
$(".photosLive").html(image);
By the way, this not clean. As I mentioned it, the best way is to use structured data.
Regards.
精彩评论