开发者

Problem parsing XML output (PHP/JQuery)

I scratch my head in frustration, but I can't find the answer. I'm new to Ajax and I'm trying this easy script:

Here's my code:

JAVASCRIPT:

$(document).ready(function(){    
    $("#toggle_album").click(function () {  
        $.post('backend/load_album_thumbnails.php', {  
            text: 'my string',  
                number: 23  
        }, function(xml) {  
                var timestamp = $(xml).find("time").text();
                alert(xml);
                alert(timestamp);
        });  
    });
});  

the alert(xml) returns:

     <? xml version="1.0"?>
<response status="ok">
<time>23:33:13</time>
<string>my string</string>
</response>

the alert(timestamp) returns emp开发者_StackOverflowty

i have also tried:

timestamp = $("time",xml).text();

with the same result.

I added the extra space in the xml start tag because it dissapeared here on stackoverflow. The only reason for this error I can think of is that the return data isn't in XML format, but I can't figure out why that would be the case.

Appreciate any answers.


You're correct, the reason it's not working is that the return data isn't in XML format. Generally, if a web server doesn't return a text/xml Content-Type header, then certain browsers (and therefore jQuery) won't bother parsing the XML.

To get it to work, your options are:

  1. Modify your response headers to specify XML format using PHP's header() function and then, change your response so that it uses well-formed XML. The code to do this would look something like:

    header('Content-Type: text/xml; charset=UTF-8');
    echo "<?xml version=\"1.0\"?>
    <response status="ok">
      <time>$timestamp</time>
      <string>$mystring</string>
    </response>";
    
  2. Change the way you handle the response in your JavaScript code (for example, write a simple regular expression parser, although this is considered bad for your health)

  3. Change your response to something like JSON so that you can use jQuery's $.getJSON() method to send the request and parse the response to a JavaScript object (PHP has some very nice built-in JSON functions).
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜