【问题标题】:Get response parameter value in ajax [duplicate]在ajax中获取响应参数值[重复]
【发布时间】:2014-07-19 21:46:59
【问题描述】:

我为轴室 API 编写了一个 sn-p。在传递 json 进行测试时,我遇到了 Cross-Origin Request Blocked 错误。

同时控制台显示:{"message":"Could not parse the message.","status":"Error"}。 (见下图)

我没有解决 Cross-Origin Request Blocked 错误。但现在我想显示 Could not parse the message 错误。怎么做?。是解决 Cross-Origin Request Blocked 错误的好方法。请给我建议。

我的 JavaScript 代码

<script type="text/javascript">
    $(function () {
        $('#Button1').click(function () {
            alert('Alter with jQuery Button Clicked');
            alert('Clicked');
            $.ajax({
                type: 'POST',
                url: 'http://test.axisrooms.com/api/daywiseInventory',
                data: '{"accessKey": "7eb228097576abf56968e9845ab51b90","channelId": "103","hotels": [{"hotelId": "2","rooms": [ {"roomId": "1", "availability": [ { "date": "2014-05-30","free": 1},{"date": "2014-05-31","free": 1}]}]}]}',
                //data: "{accessKey':'cilentAPIKey'}",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (data) {
                    callback(data);
                    alert('sus'+data.toString());
                },
                error: function (response) {
                    //alert(response);
                    //alert('error' + response.valueOf(message));                    
                    alert('An error has occured');
                }

            });
        });
    });
</script>

【问题讨论】:

  • JSON 规则 #1:不要尝试手动构建 JSON。 您的数据参数无效。 (只需传递一个对象并让 jQuery 构建对象,即删除双引号。)
  • 看看我的新编辑先生,现在我更改了正确格式的 json。至于CORS问题,谁想编码先生。我还是轴公司(谁创建了 API)?

标签: javascript jquery ajax json


【解决方案1】:

首先你的 json 格式不正确。

转到 jsonlint 并将您的 json 粘贴到那里。我想你必须使用这样的双人床。

测试一下,如果不行就回来。

{
    "accessKey": "7eb228097576abf56968e9845ab51b90",
    "channelId": "103",
    "hotels": [
        {
            "hotelId": "2",
            "rooms": [
                {
                    "roomId": "1",
                    "availability": [
                        {
                            "date": "2014-05-30",
                            "free": 1
                        },
                        {
                            "date": "2014-05-31",
                            "free": 1
                        }
                    ]
                }
            ]
        }
    ]
}

【讨论】:

  • 谢谢先生,现在我解决了 Json 格式。但没有任何改变。 :-(
【解决方案2】:

对于跨源请求,您无法通过 javascript 获取 XHR 对象的响应状态、代码或标头...您只是获得了成功状态,但响应为空。

【讨论】:

  • 我是 API 方面的新手,先生。这是我的尝试。所以请多解释一下。
  • 正如你所说,它是跨域请求被阻止......除了接受响应为空之外,你什么也做不了。除非您在服务器端实施一些跨源解决方案。
  • 谢谢先生。我将此消息传递给轴。
猜你喜欢
  • 2016-04-27
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2020-02-17
  • 1970-01-01
相关资源
最近更新 更多