html Ajax单个首先解析Json数据(JSON不是对象)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html Ajax单个首先解析Json数据(JSON不是对象)相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<!-- <script type="text/javascript" src="/ajax-util.js"></script> -->
<!-- <script type="text/javascript" src="/script.js"></script> -->
<!-- <script type="text/javascript" src="/ajaxUTL.js"></script> -->
<title>Practice test</title>
<script type="text/javascript">
(function(global) {
//namespace to attach things to global
var ajaxScatola = {};
var isJsonResponse;
//return HTTP Request Obj/ not avail to global
function getRequestObject() {
if(window.XMLHttpRequest) {
return new XMLHttpRequest();
}//if
else if(window.ActiveXObject) {
//old IE
return new ActiveXObject("Microsoft.XMLHTTP");
}//else
else {
global.alert("Ajax is not supported");
return null;
}
}//getRequestObject
//Ajax GET request
ajaxScatola.sendGetRequest = function(requestUrl, responseHandler,isJsonResponse) {
//get request obj
var request = getRequestObject();
//onreadystate - when server comesback with response we call handleResponse
request.onreadystatechange =
function() {
handleResponse(request, responseHandler, isJsonResponse);
};
//then open GET
request.open("GET", requestUrl, true);
request.send(null); //for POST only
};//fn
//Only calls user provided responseHandler
function handleResponse(request, responseHandler) {
if((request.readyState == 4) &&
(request.status == 200)) {
//default-to-true
if(isJsonResponse == undefined) {
isJsonResponse = true;
}//isJson
if(isJsonResponse) {
responseHandler(JSON.parse(request.responseText));
}
else {
responseHandler(request.responseText);
}
}//if-readyState-status
}//fn
//Expose utility to global object ot use it
global.FacingOutAjax = ajaxScatola;
})(window);
</script>
</head>
<body>
<h1 id="title">ajax test</h1>
<p>
<button>
Say hello to someone on the Server!
</button>
</p>
<div id="content">
</div>
<script type="text/javascript">
//Event handler
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelector('button').
addEventListener('click', function() {
//call server to get name
FacingOutAjax.sendGetRequest("/name.json", function(res) {
var message =
res.firstname + " " + res.password
if(res.likesChineseFood) {
message += " likes Chinese Food";
}
else {
message += " doesn't like Chinese Food";
}
message += " and has an id of " + res.id;
document.querySelector('#content')
.innerHTML = "<h2>" + message + "</h2>";
});
}); //click event
}); //DOMContentLoaded
</script>
</body>
</html>
以上是关于html Ajax单个首先解析Json数据(JSON不是对象)的主要内容,如果未能解决你的问题,请参考以下文章