请您查看This Demo并告诉我如何访问JSON对象,例如credit
,它在同一个请求者脚本中声明:
var credit = [{
"name": "John Johnson",
"street": "Oslo West 16",
"phone": "222 7894562"
}, {
"name": "Davie Amber",
"street": "Alberta 52",
"phone": "555 1234567"
}, {
"name": "Marck William",
"street": "Delestre 125",
"phone": "666 7254599"
}];
$("button").click(function () {
$.ajax({
url: "credit",
success: function (result) {
$("#div1").html(result);
}
});
});
我知道在现实世界中,没有必要这样做,因为在简单的JavaScript中是可行的,但是为了进行特定的测试,我需要提供像$.ajax()
方法运行的测试环境。
由于
答案 0 :(得分:1)
mockjax可能就是你要找的。 p>
Here是你的例子,有一些调整让它输出到div(由于mockjax脚本的mime类型,我没有在chrome中工作)
HTML
<div id="div1"></div>
<button>Get Data</button>
的Javascript
$(document).ready(function () {
$.mockjax({
url: '/someurl',
responseText: [{
"name": "John Johnson",
"street": "Oslo West 16",
"phone": "222 7894562"
},
{
"name": "Davie Amber",
"street": "Alberta 52",
"phone": "555 1234567"
},
{
"name": "Marck William",
"street": "Delestre 125",
"phone": "666 7254599"
}]
});
$("button").click(function () {
$.ajax({
url: "/someurl",
success: function (result) {
console.log(result);
$("#div1").html(JSON.stringify(result));
}
});
});
});