我有一个button
我称之为AJAX函数:
<button class="loadProduct" onclick="loadProduct(7)" type="button">Load product</button>
这是我的AJAX功能:
var loadProduct = function (idProduct) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var product = JSON.parse(xhttp.responseText);
alert(product);
}
xhttp.open("GET", "http://localhost/product/loadProduct/" + idProduct, true);
xhttp.send();
};
};
它应该向服务器发送请求并获取产品,但它不会显示警报。
我认为这与数据响应有关,但如果我直接转到链接
http://localhost/product/loadProduct/7
我收到以下回复:
{"idProduct":"7","name":"product7"}
因此我怀疑AJAX函数没有调用此链接,因为响应正在正确发送(如果您直接访问它)。
提前致谢!
答案 0 :(得分:2)
只需打开控制台并检查请求......
答案 1 :(得分:2)
您需要在onreadystatechange
功能之外移动实际通话:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var product = JSON.parse(xhttp.responseText);
}
};
xhttp.open('GET', 'http://localhost/product/loadProduct/' + 1, true);
xhttp.send();