[英]Convert JSON string in html into JSON object
我從MarkitOnDemand API檢索了JSON格式的一些數據,我想要的JSON內容在html字符串的body標簽內,如下所示:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Autocompelete</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
{"Status":"SUCCESS","Name":"Apple Inc","Symbol":"AAPL","LastPrice":109.59,"Change":1.91,"ChangePercent":1.77377414561664,"Timestamp":"Wed Mar 30 15:59:00 UTC-04:00 2016","MSDate":42459.6659722222,"MarketCap":607630850970,"Volume":3211276,"ChangeYTD":105.26,"ChangePercentYTD":4.11362340870226,"High":110.41,"Low":108.6,"Open":108.64}</body>
</html>
上面的html字符串代碼位於我的AJAX調用的“data”字符串中:
$(function(){
$('#searchform').on('submit', function(event){
event.preventDefault();
var requestdata = 'symbol=' + $('#query').val();
$.ajax({
url: "receivesearch.php",
method: "get",
data: requestdata,
success: function(data){ //html string in this data parameter
//CONFUSED HERE
}
});
});
});
但是我沒有從body標簽中獲取JSON字符串並將其解析為JSON對象...
誰有人可以幫我解決這個問題? 非常感謝!!
這是我的PHP代碼:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Autocompelete</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<?php
if(isset($_GET['symbol'])){
$lookupURL = "http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol=" . $_GET['symbol'];
$jsonhtml = file_get_contents($lookupURL);
echo $jsonhtml;
}
?>
</body>
</html>
您需要將結果解析兩次:一次使用$.parseHTML()
作為HTML,然后您可以從中獲取文本並將其傳遞給$.parseJSON()
。
這些方面的東西:
success: function(data){ //html string in this data parameter
var html = $.parseHTML(data);
var body = $(html).text();
var json = $.parseJSON(body);
// use the JSON data here
}
Markit On Demand API支持JSON,因此您的原始查詢有問題。
請查看此URL以獲取示例:
http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol=AAPL
它返回純JSON數據,可以使用$.parseJSON(data)
更新:嘗試此代碼,例如:
var requestData = 'symbol=AAPL';
$.ajax({
url: "http://dev.markitondemand.com/MODApis/Api/v2/Quote/json",
method: "get",
data: requestdata,
success: function(data){ //html string in this data parameter
$symbolResponse = $.parseJSON(data);
}
});
更新2:使用此PHP代碼:(只是這個代碼,沒有別的)
<?php
if (isset($_GET['symbol'])) {
header('Content-Type: application/json');
$lookupURL = "http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol=" . $_GET['symbol'];
$jsonhtml = file_get_contents($lookupURL);
echo $jsonhtml;
}
?>
您可以選擇JSON.parse(data)
, $.parseJSON(data)
或未建議的eval(data)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.