2012-03-19 43 views
1

我有一個url正在返回JSON,但由於跨瀏覽器請求問題,我用CURL在PHP中請求它,現在它以字符串形式返回json數據。我想要將該字符串轉換爲json,以便我可以將其與javascript函數一起使用。url數據到json

Ajax請求它打印JSON字符串

$.ajax({ 
     url: 'tweet.php', 
     cache: false, 
     dataType: 'json', 
     type: 'POST', 
     data: { 
      url : url, 
     }, 
     success: function(tweet){ 
      var tweets = $.parseJSON(tweet); 

      console.log(tweets); 
     } 
    }); 

和tweet.php

header('Content-type: application/json'); 
$ch = curl_init() or die('cURL not available'); 
curl_setopt($ch, CURLOPT_URL, $_POST["url"]. $location); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $options); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output 
$result = curl_exec($ch); 
curl_close ($ch); 
print ($result); 

獲得解決

雖然答案沒有無效的JSON錯誤

幫助,但不知何故,我想出來。如果有人需要,請在這裏發帖。

每當您使用Curl從PHP請求JSON時,它都會返回JSON對象,但作爲字符串,您可以通過javascript typeof()函數進行檢查。如果你想將該字符串轉換爲真正的JavaScript對象,你需要使用某種解析器。這裏我用 JSON PARSER

var myJson = '{ "x": "Hello, World!", "y": [1, 2, 3] }'; 
var myJsonObj = jsonParse(myJson); 
console.log(myJsonObj); 

問候

+2

JSON數據串是JSON。那麼,爲什麼你不能簡單地回顯/打印返回值呢? – Candide 2012-03-19 09:40:23

+0

這可能是http://stackoverflow.com/questions/921374/how-do-i-convert-a-json-string-to-a-javascript-object-in-jquery – 2012-03-19 09:42:13

+0

的副本還可以看看http://stackoverflow.com/questions/682260/returning-json-from-php-to-javascript – 2012-03-19 09:44:10

回答

1

嘗試jQuery.parseJSON

另外,作爲一個額外的,如果你希望你的php迴應被視爲JSON內容在PHP中使用下列模式:

// Convert to JSON 
$json = json_encode($yourData); 

// Set content type 
header('Content-type: application/json'); 

// Prevent caching 
header('Expires: 0'); 

// Send Response 
print($json); 

exit; 
+0

此外,它不清楚爲什麼簡單地獲得這與$ .getJSON(url)不會工作...無論服務器端在做什麼,如果它返回一個有效的JSON,那麼它仍然是解析 – poncha 2012-03-19 09:43:28

+0

未捕獲無效JSON:這是我得到的錯誤,當我在php – 2012-03-19 09:44:19

+0

中執行「echo」時,getJSON將不起作用,因爲源不是源於同一個源。 – 2012-03-19 09:44:52

1

在你的html文件中這樣做假設$json持有返回的字符串形式的遠程URL

<script type="text/javascript"> 
var data = JSON.parse("<?php echo $json; ?>"); 
</script> 
0

變化的dataType'文本''JSON'在$就調用