开发者

Using jQuery ajax response data

I am using ajax post and am receiving data in the form of html. I need to split up the data and place pieces of the data all over the page. I built my response data to be something like <p id='greeting'> Hello there and Welcome </p> <p id='something'>First timer visiting our site eh'</p> It is a little more complicated and dynamic but I can figure it out if get this question answered. Thanks

$.ajax({
            type:'POST',
            url: 'confirm.php',
            data: "really=yes&sure=yes",
  开发者_运维问答          success:function(data){
                    //Need to split data here
            }
        });


Update: Just realized you should probably do this:

success:function(data) {
    data = $('<div/>').append(data);
    $('#greeting',data).appendTo('#one')
    $('#something',data).appendTo('#two')
}

As you cant use .find properly since it isnt a child but if you append it to an empty node you can. The other alternative would be using .filter

$.ajax({
            type:'POST',
            url: 'confirm.php',
            data: "really=yes&sure=yes",
            success:function(data){
                    $('#greeting',data).appendTo('#one')
                    $('#something',data).appendTo('#two')
            }
        });

You can extract from data and append where you want to. You can also do something like return JSON instead, and instead of extracting html from html just access the html from an object.

$(data.greeting).appendTo('#one')
$(data.something).appendTo('#two')

The response would have to be like:

({ 'greeting':'html', 'something' :'other html' })


Why don't you string the answers together within confirm.php with the | character, then when the string gets returned as the variable data you can split it with datas = data.split("|") and access the individual answers with data[0], data[1], etc.


(Meder's response will work if you are comfortable with JSON, but regular expressions are probably a little easier and will work just as well for this.)

You will probably need to break up the response text using regular expressions. For example, if the response text is:

<p id='greeting'> Hello there and Welcome </p>
<p id='something'>First timer visiting our site eh'</p>

Then you could use some JavaScript like this:

var greeting = response_text.match(/<p id='greeting'>.*</p>/);
var something = response_text.match(/<p id='something'>.*</p>);

(This site is great for learning about regular expressions: http://gskinner.com/RegExr/)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜