【问题标题】:What is the correct syntax for winjs.xhr datawinjs.xhr 数据的正确语法是什么
【发布时间】:2014-05-23 19:23:03
【问题描述】:

我尝试使用 winjs.xhr 将一些数据发布到 URL,但没有成功。我通过基本上用 XMLHttpRequest 做同样的事情来让它工作。这感觉不对,因为我认为 winjs.xhr 无论如何都会包装 XMLHttpRequest。谁能解释我是如何在 winjs.xhr 中做到这一点的?

winjs.xhr 代码不工作

将所有内容作为 URL 编码字符串传入

var url = "http://localhost/paramecho.php";

var targetUri = "http://localhost/paramecho.php";
var formParams = "username=foo&password=bar" //prefixing with a '?' makes no difference
//ends up with same response passing an object(below) or string (above)
//var formObj = {username: "foo", password: "bar"} 

WinJS.xhr({
    type: "post",
    url: targetUri,
    data: formParams

}).then(function (xhr) {
    console.log(xhr.responseText);
});

最终我收到的 PHP 文件没有得到任何参数,就好像我一开始没有发送任何数据一样。

我尝试了一些方法,但上面的代码是最简单的示例。如果我要将一个对象传递给 data 参数,它的行为方式相同(已注释掉)。我使用了一个 FormData 对象以及一个普通的 JSON 对象。

我更改了我的应用清单以具有正确的网络功能 - 下面的工作示例是在同一个应用中完成的,所以我确信它与功能无关。

使用 XMLHttpRequest 的工作版本

var username = "foo";
var password = "bar";
var request = new XMLHttpRequest();
try {
    request.open("POST", "http://localhost/paramecho.php", false);
    request.setRequestHeader('Content-type', "application/x-www-form-urlencoded");
    request.send("username=" + encodeURIComponent(username) + "&password=" + encodeURIComponent(password));
    console.log(request.responseText);
} catch (e) {
    console.log("networkError " + e.message + "   " + e.description);
}

这成功地调用了我的 PHP 服务器端函数,并使用了我期望的参数。

所以,问题是......我如何使用 winjs.xhr 实现我在 XMLHttpRequest 中的工作?感觉就像 winjs.xhr 应该工作的方式(我是 Windows 8 应用程序开发的新手,所以我很高兴得到纠正)

【问题讨论】:

  • 它只是一个薄包装。它不会自动设置内容类型的标题。您将在工作示例中看到您添加了标头,但在 WinJs 版本中,您没有。

标签: windows-8.1 winjs


【解决方案1】:

你说得对,WiredPrairie。只需要传入标题 - 我想我认为这是帖子的默认设置。

工作版本:

WinJS.xhr({
    type: "post",
    url: targetUri,
    data: formParams,
    headers: {"Content-type": "application/x-www-form-urlencoded"}
}).then(function (xhr) {
    console.log(xhr.responseText);
});

【讨论】:

    最近更新 更多