开发者

Displaying the JSON in HTML input boxes using AJAX?

开发者 https://www.devze.com 2023-01-27 11:09 出处:网络
I\'m very new at AJAX and Javascript and need a bit of help with this code. Here is the bit of JSON I\'m using

I'm very new at AJAX and Javascript and need a bit of help with this code.

Here is the bit of JSON I'm using

{"URL":"www.youtube.com","Total URLs":132,"Completed":63}

I need to get each one of these values and display in different HTML input text boxes using AJAX.

Current URL: <input type="text" name="urlqueue">
Total URLs: <input type开发者_JS百科="text" name="total">
Completed: <input type="text" name="completed">

Right now I have

 ajaxRequest.onreadystatechange = function(){
  if(ajaxRequest.readyState == 4){
   document.form.total.value = ajaxRequest.responseText;
  }
 }
 ajaxRequest.open("GET", "test_results.php", true);
 ajaxRequest.send(null); 

You can see this doesn't work anymore. I use to have the file containing only 1 number and no JSON. Now I need to use the file for many results with JSON and need some direction.

How do I display the JSON in the HTML input boxes using AJAX?


Parse the JSON, either by using a JSON parsing library or by using eval. Note that using eval can be very dangerous, as you can introduce cross-site scripting vulnerabilities if it is used incorrectly.

The resulting object will have the values, so you can set each field individually by, for example:

document.form.total.value = jsonObject["Total URLs"];


Note that when you make an AJAX and retrieve the response, the response text is not JavaScript object. It's just string so you should evaluate the string to JavaScript Object. The following code will produce that in a quick way. But Douglas Crockford who is the master of JavaScript says that "eval is evil".

var data = eval('(' + ajaxRequest.responseText + ')');
document.form.total.value = data[Total URLs]

also I want to remember that avoid spaces in property names. For example, you should have a property named "Total_URLs" or "TotalURLs" etc. instead of "Total URLs"

0

精彩评论

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