How to use multiple values with jQuery ajax dataType?

狂风中的少年 提交于 2019-12-24 02:23:47

问题


I should request the data as jsonp to perform cross domain request. But actual result returned is json like {"q":"iphone","r":["iphone 5","iphone","обмен на iphone","iphone 4","iphone 5s"]}.

I've tried to use multiple values in dataType like:

$.ajax({
  url: url,
  type: 'GET',
  dataType: 'jsonp json',
  jsonp: false,
  ... 

but it returns parsererror (the same as just with jsonp).

I also tried to do the call with and without callback:

$.ajax({
  url: url,
  type: 'GET',
  dataType: 'jsonp json',
  cache: true,
  jsonpCallback: 'callbackFunctionName',
  jsonp: 'callback',

What can I do to process such result correctly?

Upd. I tried to use script instead of jsonp, it works better - success/done function is called (instead of error/fail), but I can not get response text - data passed to success() is undefined as well as jqXHR.responseText passed to complete() is empty.


回答1:


You can't use multiple dataTypes, if you use JSONP this will return a JSONP block which you could use to call a callback to handle the return data like this:

  • Basic example of using .ajax() with JSONP?

You want to return a response formed as a JSONP block which would be something like:

callback({
    "q": "iphone",
    "r": ["iphone 5", "iphone", "обмен на iphone", "iphone 4", "iphone 5s"]
});

From here you can use the callback assuming that you are using the AJAX call with the set callback parameter.




回答2:


If you need to return multiple datatypes from the URL then there is no need to pass the dataType in jQuery AJAX call.

$.ajax({
        type: "GET",
        url: url,
        data: data,
        //dataType: "json",  comment this line
        cache: false,
        beforeSend: function () {},
        success: function (data) {},
        error: function (xhr, ajaxOptions, errorThrown) {}
      });


来源:https://stackoverflow.com/questions/25684026/how-to-use-multiple-values-with-jquery-ajax-datatype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!