我从 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>
最佳答案
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;
}
?>
关于javascript - 将html中的JSON字符串转换为JSON对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36321737/