xmlhttprequest对象正常工作,但没有给出响应输出? [英] xmlhttprequest object working but not giving output in response?

查看:268
本文介绍了xmlhttprequest对象正常工作,但没有给出响应输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,其中我正在调用getlink.php脚本以获取给定文件的链接.但是当我做alert(xhr.responseText)时,它什么也没显示.但是,如果我在控制台上将console.log("my object: %o", xhr);输出为responseText字段. 代码是:

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);
}

推荐答案

在xhr.open中使用true时,会将其设置为异步,这意味着响应将稍后返回,您需要通过附加侦听器来收集响应.

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.

如果您将该参数设置为false,则您的代码可以工作(但不会异步并且会阻止调用(意味着它将一直坐在那里直到响应返回))

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)

这是添加侦听器的方法(因为您的异步方法实际上是更好的方法)... http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

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

这篇关于xmlhttprequest对象正常工作,但没有给出响应输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆