开发者

No response when using AJAX and JSON

function getIDs() {
alert("1");
var title = document.getElementById('title').value;
alert(title);
title = "http://www.imdbapi.com/?i=&t=" + title;
alert(title);
xmlhttp=new XML开发者_如何学运维HttpRequest();
alert("2");
xmlhttp.open("GET",title,true);
alert("3");
xmlhttp.send();
alert("4");
var imdbData = xmlhttp.responseText;
alert(imdbData);
var imdbJSON = JSON.parse(imdbData);
//document.getElementById('title').value = imdbJSON.Title;
alert(imdbJSON.Title);
document.getElementById('imdbid').value = imdbJSON.ID;
return true;
}

I'm trying to fetch the ID of a film based upon it's title, the function gets called successfully and the alerts are correct until the alert which returns "imdbData", which returns a blank alert, then no more alerts occur, I'm unsure where I'm going wrong here. Any assistance would be appreciated.


You're opening it asynchronously. To make it synchronous, change this:

xmlhttp.open("GET",title,true);

To this:

xmlhttp.open("GET",title,false);

A usually-considered-better way would be to make it work with asynchronicity:

function getIDs() {
    alert("1");
    var title = document.getElementById('title').value;
    title = "http://www.imdbapi.com/?i=&t=" + title;
    xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if(xmlhttp.readyState==4) {
            var imdbData = xmlhttp.responseText;
            var imdbJSON = JSON.parse(imdbData);
            document.getElementById('title').value = imdbJSON.Title;
            document.getElementById('imdbid').value = imdbJSON.ID;
        }
    };
    xmlhttp.open("GET",title,true);
    xmlhttp.send();
    return true;
}

Additionally, you cannot request pages from other domains. You may need to switch to JSONP if the API you're using supports it, or use your web server as a proxy.


You are not allowed to do cross site scripting with JavaScript which is why you get nothing in return. You need to be on the same domain as you post your AJAX call to.

Use a serverside script to parse the URL for you instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜