我需要将JSON结果存储在某个变量中,然后我想在html的BODY中使用该变量。
以下是我在“测试”警报中无法获取任何内容的代码。
<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var msg;
$(document).ready(function () {
var msg1;
$.ajax({
url: "http://rest-service.guides.spring.io/greeting"
//var msg2;
}).then(function(data) {
json_list = data.id;
msg= data.id;
msg1= data.id;
var $temp = $('.class1').append(data.content);
//alert($temp);
//msg2= data.id;
/* $('.greeting-content').append(data.content); */
alert("Inside AJAX "+data.content);
$('#content').html(data.content);
//msg=$('#content').html();
//return msg;
// $('.greeting-id').append(data.id);*/
// alert(msg);
});
});
</script>
<div id="content"></div>
<div class="class1">
</div>
<script>
var test1=$('#content').contents();
alert("Test Result -- " +test1);
</script>
</body>
</html>
你能告诉我如何实现这个目标吗?
我想将JSON值存储在test1变量中(在BOLD中)。
如果需要进一步的信息,请告诉我。
答案 0 :(得分:1)
Ajax不是时间旅行。
您的代码:
#content
的内容并将其放入变量中,然后发出警报。#content
在那个阶段,分配变量的代码已经运行了。警告该变量值的代码已经运行。
如果您想对该内容采取任何措施,请在成功处理程序内执行。
答案 1 :(得分:0)
只需将数据传递给parseJSON(数据),然后再使用
$(document).ready(function () {
var msg1;
$.ajax({
url: "http://rest-service.guides.spring.io/greeting"
//var msg2;
}).then(function(data) {
// see here i change.
var data_json = jQuery.parseJSON(data);
json_list = data_json.id;
//bellow is function.
passinganotherscript(json_list);
msg= data_json.id;
msg1= data_json.id;
var $temp = $('.class1').append(data_json.content);
$('#content').html(data_json.content);
});
function passinganotherscript(data){
//here you are able to access your value of data.
}
我希望这会对你有所帮助