将php或xmlhttp.responseText中的列表传递给javascript

I have a list in javascript that is to be changed by the content of a database when the user clicks a link or slides a bar. I currently use a xmlhttp request to fetch a php page which generates the list. I have a static list working in this form:

var mark_list = [
{ "EntID" : 3, "x" : 100, "y" : 400},
];

I tried to have the php page generate the { "EntID" : 3, "x" : 100, "y" : 400} and set mark_list equal to responseText but I believe that's just a string. I'm struggling to find a way to get this new list into the variablie.

Does anyone have any suggestions or solutions? Your help would be greatly appreciated.

Kallum

Make sure the browser has a JSON object by including the json script from here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

It will defer to the native browser JSON object if available, and if not, will add it so that this functionality is available in browsers that don't currently support it.

Then in your code, after you receive the output from the PHP script, run this:

var mark_list = JSON.parse(responseText);

Based on the output from the PHP script, you may need to do this:

var stuff = JSON.parse(responseText);
var mark_list = [stuff];

This will convert the JSON string the PHP returns into an actual javascript object.

In your PHP code you can do something like this:

$output = array(
    array(
        'EntId' => 3,
        'x' => 100,
        'y' => 400,
    ),
);

echo json_encode($output);

Then you can use the var mark_list = JSON.parse(responseText); option in your JavaScript.

responseText will indeed just be a text represented by a string, so the way you are outputting it right now won't just do the trick all on its own. There are basically two ways you can do this:

  • In your javascript, you parse the output the server is giving you. This can be done onn a pure string in whatever way you feel like doing it. For example, you could write javascript to parse the format you gave with curly braces and a colon based syntax. Alternatively, you could use another format (like XML) which will reduce the work a little, but will still leave the interpreting of the output for you to do in the javascript.

  • You can output to a format used to describe objects and lists. JSON would be the big example of such a format. If you output in JSON, you will get something that resembles the format you used above (JSON stands for Javascript Object Notation and is based on parts of the syntax of javascript) and all you will have to do to be able to use it is to get to the data you want to get to. You can use JSON.parse() for this on most browsers, but an alternative with more widespread support is jQuery's jQuery.parseJSON() (for which you would use jQuery, which you should also provide in that case)