我有这个函数从php文件调用JSON
function ajax_json_data(){
var div = document.getElementById("div");
var hr = new XMLHttpRequest();
hr.open("POST", "test.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
div.innerHTML += '<img src="images/'+d.num1.imageName+'" alt="'+d.num1.imageName+'" />';
}
}
hr.send(null);
}
这是php文件输出的内容
{
"num1":{ "imageName":"img1.jpg","imgTitle":"Title1", "description":"desc1" },
"num2":{ "imageName":"img2.jpg","imgTitle":"Title2", "description":"desc2" },
"num3":{ "imageName":"img3.jpg","imgTitle":"Title3", "description":"desc3" }
}
我的菜鸟问题是如何从锚标记中定位num2
,如<; p>
<a href="#" onClick="ajax_json_data('num2')">Next Image</a>
我试过了
function ajax_json_data(x){
//XMLHttpRequest
var d = JSON.parse(hr.responseText);
div.innerHTML += '<img src="images/'+d.+x+.imageName+'" alt="'+d.+x+.imageName+'" />';
hr.send(null);
}
但这些错误可以让任何人帮忙吗?
这是我的解决方案
div.innerHTML += '<img src="images/'+d.[x].imageName+'" alt="'+d.[x].imageName+'" />';
代码和学习