我已经尝试通过jQuery / ajax来执行此操作,但是它没有用,所以我认为我会退回到普通的XMLHttpRequest上。不幸的是,它仍然无法正常工作(同样的问题)。

这是Google's POST request的文档。这是我的代码:

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”以以下形式发送到控制台:longUrl = http%3A%2F%2Fwww.google.com%2F

响应为:

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


有人看到我在做什么错吗?

提前致谢!

编辑:为@Greg添加-以便您可以看到我在使用jQuery时遵循Google的规格-导致完全相同的错误。

$.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);

09-10 07:25
查看更多