开发者

Problem with Javascript, AJAX & JSON

I'm an iPhone Developer whose quite new to web development so please forgive me if I'm making silly mistakes here:

What I'm trying to accomplish is when the user selects an item from a drop-down开发者_开发百科, it calls some javascript, which sets off an AJAX request to a PHP file I have which returns some JSON. - That JSON includes a thumbnail image filename, and a caption for the image. These need to be passed in to an image, and textfield respectively in my document.

The problem is, it fails after trying to eval the json. - The same happens with eval(json); and JSON.parse(json); I worked this out by calling document.write('something'); periodically in my response method. - It will always be able to write up to the point where it parses the json.

I am sure my PHP is valid and my request is good (I can output the response from the JS fine).

Here is the function I call when a new item is selected in the drop-down:

function changeImage(id){
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        var res=xmlhttp.responseText;
        var responseObject = eval(res);
        var caption = responseObject.caption;
        var textField = document.getElementById('caption');
        textField.value = caption;
        var imagePreview = document.getElementById('imgPreview');
        imagePreview.src = responseObject.filename;
        }
      }
    xmlhttp.open("GET","getCaption.php?id="+id,true);
    xmlhttp.send();
}

When I output res (or access the php file manually) the JSON looks like this:

{"caption":"A caption","filename":"myimage_thumb.jpg"}

why is the JSON eval failing?

UPDATE: This error is logged: SyntaxError: Parse error


You're taking a JSON string and pretending that it's a Javascript object literal. But, remember, JSON is merely named after Javascript's object notation!

You're then hoping that eval will directly evaluate this and return an object, but this is not the case.


Observations

Writing the following in the Firebug console:

eval('{"caption":"A caption","filename":"myimage_thumb.jpg"}')

will also yield a SyntaxError. (Ideally, you'd have narrowed your problem down to this!)

Interestingly, constructing an object more explicitly does work (for this input):

eval('new Object({"caption":"A caption","filename":"myimage_thumb.jpg"})')

As does just forcing the input into being a certain kind of expression, with parentheses:

eval('({"caption":"A caption","filename":"myimage_thumb.jpg"})')

Explanation

It all comes down to this statement from 12.4 in the ECMAScript standard:

Note that an ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block.

This article explains the issue in depth, but in summary the solution is to use JSON.parse(res) to obtain an object from a JSON string. This is the proper approach, and it will not fail as long as your input is valid JSON.


Change the eval-line against:

eval('var responseObject = ' + res);


You might want to try:

eval("(" + res + ")");

so that it wraps it in (...). I'm not sure why yet.

Anyway, you could also look into jQuery, because then it's as simple as:

$.getJSON("path", function(json) {
    // json is the ready-to-use object
});


There are a couple of suggestions that I would give in this context

  • Can you try doing a console.log(res) or alert(res), so that you know you really have a res before you try using it.

  • Never use eval(res). Why not use JSON.parse(res) (on modern browsers, since you have IE5 browsers too up there), or even better $.parseJSON (if using jQuery)

  • If you are sending if from PHP, use json_encode($var, JSON_HEX_TAG|JSON_HEX_APOS) to prevent syntax errors while parsing. Check my answer (link below) in another thread.

    How to store a php array on the client side?


This is how I use eval -

var rsltObj = eval('(' + jsonStr + ')');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜