xmlhttprequest object working but not giving output in response?

非 Y 不嫁゛ 提交于 2019-12-08 09:33:12

问题


i have following code in which i am making a call to getlink.php script to get a link of given file. But when i do alert(xhr.responseText) it does not show anything. But if i output on console as console.log("my object: %o", xhr); it gives responseText field. code is:

function linkFile(file) {  
    uri = "http://localhost/imgbag/getlink.php";  
    var xhr = new XMLHttpRequest();  
    var formdata= new FormData();
    formdata.append("linkFile",file);
    xhr.open("POST", uri, true);  
    xhr.send(formdata);
    console.log("my object: %o", xhr);
}

回答1:


when you use true in xhr.open it sets it to be async which means the response will come back later and you need to collect it by attaching a listener.

if you set that param to false your code will work (but will not be async and will block on the call (meaning it will just sit there till the response comes back)

here's how to add a listener (because your async approach is actually the better one)... http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp




回答2:


Define the onload attribute like this :

xhr.onload = function () {
    alert(xhr.responseText);
}

This ensures that the alert takes place only after the request has been successfully completed.

Sources : MDN



来源:https://stackoverflow.com/questions/10847432/xmlhttprequest-object-working-but-not-giving-output-in-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!