2010-07-29 17 views
1

HI,JSON PHP使用Javascript - 簡單的工作實例

我使用下面的代碼

request.js

var request; 
function runAjax(JSONstring) 
{ 

    // function returns "AJAX" object, depending on web browser 
    // this is not native JS function! 
    request = new XMLHttpRequest(); 

    request.open("GET", "request.php?json="+JSONstring, true); 
    request.onreadystatechange = sendData; 
    alert('called'); 
    request.send(null); 
} 

function sendData() 
{ 
    // if request object received response 
    if(request.readyState == 4) 
    { 
    // parser.php response 
    var JSONtext = request.responseText; 
    // convert received string to JavaScript object 
    try 
    { 
    //var JSONobject = eval('(' + JSONtext + ')'); 
    var JSONobject = JSON.parse(JSONtext); 
    } 
    catch(e) 
    { 
    var err="Error: "+e.description; 
    alert(err); 
    } 
alert('1'); 
    // notice how variables are used 
    try { 

    var msg = "Number of errors: "+JSONobject.errorsNum+  "\n- "+JSONobject.error[0]+  "\n- "+JSONobject.error[1]; 

    alert(msg); 
    } 
    catch(ee) 
    { 
    var errr="Error: "+ee.description; 
    alert(errr); 
    } 
    } 
} 

我在這裏使用的PHP函數是request.php

<?php 

// decode JSON string to PHP object 
$decoded = json_decode($_GET['json']); 

// do something with data here 
echo "Decoded string - ". $decoded; 
// create response object 
$json = array(); 
$json['errorsNum'] = 2; 
$json['error'] = array(); 
$json['error'][] = 'Wrong email!'; 
$json['error'][] = 'Wrong hobby!'; 

// encode array $json to JSON string 
$encoded = json_encode($json); 


// send response back to index.html 
// and end script execution 
die($encoded); 

?> 

我打電話從HTML網頁此JavaScript函數request.html

<html> 
<head> 
<script src="request.js"> 
</script> 
</head> 
<body> 
<a href="Javascript:runAjax('vinoth')">call</a><br> 
</body> 
</html> 

這裏的問題是,我在該行獲得語法錯誤:24

var JSONobject = JSON.parse(JSONtext); 

,如果我是使用

var JSONobject = eval('(' + JSONtext + ')'); 

我得到「 )預期錯誤「

之後,我刪除了瀏覽器緩存。重新啓動瀏覽器,現在代碼似乎工作得很好。

+0

嘗試'alert(JSONtext)'。它說什麼?究竟? – MvanGeest 2010-07-29 09:59:00

+0

我試過刪除所有緩存並重新安裝我的瀏覽器。我的解析器出現問題。我剛剛糾正了它。上面的代碼工作得很好。 謝謝你MvanGeest – 2010-07-29 10:26:03

回答

0

您應該驗證JSON格式,然後在那裏查找 - http://ru.wikipedia.org/wiki/JSON。你可以得到一個想法。

+0

我改變了這個問題作爲例子。對不起,如果我違反了論壇規則。 – 2010-07-29 12:24:23