我有一个javascript范围问题我想从ajax调用中获取响应文本并将其放入全局变量中。然后在另一个函数中处理JSON,这是我的代码。
var JSONDATA = "not gatherd";
var ajaxCalls = (function(){
var ajaxer = {
defaults:{
url:"test.php",
DirectHTML: true,
element:"#ajaxerizer"
},
setup:function(setup){
var defaulLengther = this.defaults
for (var key in defaulLengther)
{
if(setup.hasOwnProperty(key))
{
this.defaults[key] = setup[key];
}
}
if(this.defaults.DirectHTML === false)
{
if (window.XMLHttpRequest) {
this.ajaxRequester = new XMLHttpRequest();
}
if (window.ActiveXObject) {
this.ajaxRequester = new ActiveXObject("Microsoft.XMLHTTP");
}
this.ajaxRequester.open('POST', this.defaults.url, true);
this.ajaxRequester.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.ajaxRequester.send();
}
this.callIt();
},
callIt:function(){
if(this.defaults.DirectHTML === true)
{
$(this.defaults.element).load(this.defaults.url);
}
if(this.defaults.DirectHTML === false)
{
this.ajaxRequester.onreadystatechange = function(){
if (this.readyState == 4) {
//This is where I have trouble
alert(this.responseText);
JSONDATA = this.responseText;//This is the data I want to process and use
alert(JSONDATA);
}
}
}
}
}
return ajaxer
})();
这是索引
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="simpleHtmlAjax.js"></script>
</head>
<body>
<div id="ajaxerizer">
<script>
ajaxCalls.setup({
url:"json.php",
DirectHTML: false,
});
alert(JSONDATA);
</script>
</div>
</body>
</html>
和JSON数据
<?php
$json = array("one" => 1,"two" => 2,"three" => 3,"four" => 4);
echo json_encode($json);
?>
感谢您的帮助。
答案 0 :(得分:0)
您已经在HTML中包含了jQuery,那么为什么不使用jQuery的AJAX辅助函数来自动处理JSON数据呢?
$.post("json.php", function (data) {
// do something with data, which should be a plain JS object:
// {"one":1, "two":2, "three":3, "four":4}
}, "json");