我试过通过jquery / ajax来做这个,但它不起作用,所以我认为我会回到正常的xmlhttprequest。不幸的是,它仍然没有工作(相同的问题)。

以下是谷歌的post请求。这是我的代码:

var xmlHttp = new XMLHttpRequest();

xmlHttp.open("POST", "https://www.googleapis.com/urlshortener/v1/url", true);
xmlHttp.setRequestHeader("Content-Type", "application/json");

var url = "longUrl=" + encodeURIComponent("http://www.google.com/");
console.log(url);

xmlHttp.send(url);
.

“URL”被发送到控制台AS:longurl= http%3a%2f%2fwww.google.com%2f

响应是:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "parseError",
    "message": "Parse Error"
   }
  ],
  "code": 400,
  "message": "Parse Error"
 }
}
.

有人会看到我做错了什么吗?

提前感谢!

编辑:为@greg添加 - 以便在我使用jQuery时在谷歌的规范之后看到I AM - 这会导致相同的确切错误。

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: { "longUrl": "http://www.google.com/" },
    url: "https://www.googleapis.com/urlshortener/v1/url",
    success: function(data) {
        //do something with the shortened url json data
        //console.log(data);
    }
});
.

有帮助吗?

解决方案

这里是解决方案(来自@greg的评论指向我的正确方向)。

var xmlHttp = new XMLHttpRequest();

xmlHttp.open("POST", "https://www.googleapis.com/urlshortener/v1/url", true);
xmlHttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");

var req = new Object();
req.longUrl = "http://www.google.com/";

var jsonStr = JSON.stringify(req);

xmlHttp.send(jsonStr);
.

其他提示

您不会遵循Google提供的规范。您应该发送json对象,如:

{"longUrl": "http://www.google.com/"}
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top