jQuery的AJAX JSON数据类型转换 [英] jQuery AJAX JSON dataType Conversion

查看:266
本文介绍了jQuery的AJAX JSON数据类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望这标题是不是的的神秘。发生了什么事是我有一个jQuery AJAX脚本,我试图用它来访问API的远程服务器,它返回一个JSON响应上。然而,API返回的JSON作为MIME类型text / html的,而不是应用/ JSON(在响应报头)。这似乎很明显,我只是需要从文本更改返回的内容类型为JSON,正确地使AJAX调用内部preT的数据。

Hopefully that title isn't too cryptic. What's happening is I have a jQuery AJAX script that I'm trying to use to access an API on a remote server, which returns a JSON response. However, the API returns the JSON as MIME type "text/html" (in the response header) instead of "application/json". It would seem obvious that I simply need to change the returned content type from text to JSON, to make the AJAX call interpret the data correctly.

不幸的是,这并非如此。我曾在许多不同的方式,所有的失败尝试这样做。我已经得到了得到这个API调用的工作最接近的是,当调试器告诉我资源跨preTED为脚本,但使用MIME类型text / html转移。而AJAX调用错误与我的调试信息转储以JSON格式jqXHR对象,它告诉我: {的readyState:4,状态:200,状态文本:parsererror}

Unfortunately, this is not the case. I have tried this in a multitude of different ways, all of which fail. The closest I've gotten to getting this API call to work is when the debugger tells me "Resource interpreted as Script but transferred with MIME type text/html". And the AJAX call errors out with my debug message that dumps the jqXHR object in JSON format, which tells me: {"readyState":4,"status":200,"statusText":"parsererror"}

下面是我的code的例子(尽管我已经在得到它的工作改变了code很多不同的方式,在我的尝试,但这个版本似乎是最接近正确的):

Here is an example of my code (although I have changed the code many various ways, in my attempts at getting it to work, but this version seems to be the closest to correct):

$.ajax({
    type: 'GET',
    url: 'http://username:api-key@www.kanbanpad.com/api/v1/projects.json',
    contentType: 'application/json',
    dataType: 'jsonp',
    converters: {
        'jsonp': jQuery.parseJSON,
    },
    success: function(data) {
        alert(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(JSON.stringify(jqXHR));
        console.log(textStatus+': '+errorThrown);
    }
});

如果任何人都可以找出我需要做的不同,使这项工作,我将非常感激。

If anyone can figure out what I need to do differently to make this work, I will be extremely grateful.

这也可能是值得一提的是,如果你复制/粘贴API网址到浏览器地址栏和砸去,它给与适当的响应头(应用/ JSON)

推荐答案

所以,除非Kanbanpad更新他们的API,它不能直接用JS访问。你将不得不使用PHP(或其他)来处理请求。

So unless Kanbanpad updates their API, it cannot be directly accessed with JS. You will have to use PHP (or some other) to handle the requests.

它的工作原理一样好,只是需要一个额外的步骤就是一切。

It works just as well, it just requires an extra step is all.

就为了任何人,一直在寻找一个解决方案。

Just for anyone that was looking for a solution.

这篇关于jQuery的AJAX JSON数据类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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