Using jQuery ajax response data

前端 未结 3 1307
眼角桃花
眼角桃花 2021-02-20 17:13

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 someth

相关标签:
3条回答
  • 2021-02-20 17:35

    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' })
    
    0 讨论(0)
  • 2021-02-20 17:35

    (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 讨论(0)
  • 2021-02-20 17:43

    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.

    0 讨论(0)
提交回复
热议问题