jquery ajax cross,jQuery Cross Domain Ajax

问题

My ajax code is

$.ajax({

type: 'GET',

dataType: "jsonp",

processData: false,

crossDomain: true,

jsonp: false,

url: "http://someotherdomain.com/service.svc",

success: function (responseData, textStatus, jqXHR) {

console.log("in");

},

error: function (responseData, textStatus, errorThrown) {

alert('POST failed.');

}

});

This is a cross domain ajax request.

I am getting correct response for the request, while checking with firebug i can see that response.

This is the response I am getting in firebug response and while accessing this url through web browser

{"AuthenticateUserResult":"{\"PKPersonId\":1234,\"Salutation\":null,\"FirstName\":\"Miqdad\",\"LastName\":\"Kumar\",\"Designation\":null,\"Profile\":\"\",\"PhotoPath\":\"\/UploadFiles\/\"}"}

But I am getting error

SyntaxError: invalid label

{"AuthenticateUserResult":"{\"PKPersonId\":8970,\"Salutation\

Whether I need to use any other method to get it works. I want to implement this in phonegap+jquery mobile app.

Also, I don't have any access to the web service

If I disable chrome web security it's working fine

回答1:

Looks like the inner JSON struct is passed along as a string. You'll have to JSON.parse() it once more to get that data as an object.

try {

responseData = JSON.parse(responseData);

}

catch (e) {}

Edit:

Try the following:

$.ajax({

type: 'GET',

dataType: "json",

url: "http://someotherdomain.com/service.svc",

success: function (responseData, textStatus, jqXHR) {

console.log("in");

var data = JSON.parse(responseData['AuthenticateUserResult']);

console.log(data);

},

error: function (responseData, textStatus, errorThrown) {

alert('POST failed.');

}

});

回答2:

Unfortunately it seems that this web service returns JSON which contains another JSON - parsing contents of the inner JSON is successful. The solution is ugly but works for me. JSON.parse(...) tries to convert the entire string and fails. Assuming that you always get the answer starting with {"AuthenticateUserResult": and interesting data is after this, try:

$.ajax({

type: 'GET',

dataType: "text",

crossDomain: true,

url: "http://someotherdomain.com/service.svc",

success: function (responseData, textStatus, jqXHR) {

var authResult = JSON.parse(

responseData.replace(

'{"AuthenticateUserResult":"', ''

).replace('}"}', '}')

);

console.log("in");

},

error: function (responseData, textStatus, errorThrown) {

alert('POST failed.');

}

});

It is very important that dataType must be text to prevent auto-parsing of malformed JSON you are receiving from web service.

Basically, I'm wiping out the outer JSON by removing topmost braces and key AuthenticateUserResult along with leading and trailing quotation marks. The result is a well formed JSON, ready for parsing.

回答3:

The response from server is JSON String format. If the set dataType as 'json' jquery will attempt to use it directly. You need to set dataType as 'text' and then parse it manually.

$.ajax({

type: 'GET',

dataType: "text", // You need to use dataType text else it will try to parse it.

url: "http://someotherdomain.com/service.svc",

success: function (responseData, textStatus, jqXHR) {

console.log("in");

var data = JSON.parse(responseData['AuthenticateUserResult']);

console.log(data);

},

error: function (responseData, textStatus, errorThrown) {

alert('POST failed.');

}

});

回答4:

If you are planning to use JSONP you can use getJSON which made for that. jQuery has helper methods for JSONP.

$.getJSON( 'http://someotherdomain.com/service.svc&callback=?', function( result ) {

console.log(result);

});

Read the below links

http://api.jquery.com/jQuery.getJSON/

Basic example of using .ajax() with JSONP?

Basic how-to for cross domain jsonp

回答5:

Here is the snippets from my code.. If it solves your problems..

Client Code :

Set jsonpCallBack : 'photos' and dataType:'jsonp'

$('document').ready(function() {

var pm_url = 'http://localhost:8080/diztal/rest/login/test_cor?sessionKey=4324234';

$.ajax({

crossDomain: true,

url: pm_url,

type: 'GET',

dataType: 'jsonp',

jsonpCallback: 'photos'

});

});

function photos (data) {

alert(data);

$("#twitter_followers").html(data.responseCode);

};

Server Side Code (Using Rest Easy)

@Path("/test_cor")

@GET

@Produces(MediaType.TEXT_PLAIN)

public String testCOR(@QueryParam("sessionKey") String sessionKey, @Context HttpServletRequest httpRequest) {

ResponseJSON resp = new ResponseJSON();

resp.setResponseCode(sessionKey);

resp.setResponseText("Wrong Passcode");

resp.setResponseTypeClass("Login");

Gson gson = new Gson();

return "photos("+gson.toJson(resp)+")"; // CHECK_THIS_LINE

}

回答6:

You just have to parse the string using JSON.parse like this :

var json_result = {"AuthenticateUserResult":"{\"PKPersonId\":1234,\"Salutation\":null,\"FirstName\":\"Miqdad\",\"LastName\":\"Kumar\",\"Designation\":null,\"Profile\":\"\",\"PhotoPath\":\"\/UploadFiles\/\"}"};

var parsed = JSON.parse(json_result.AuthenticateUserResult);

console.log(parsed);

Here you will have something like this :

Designation

null

FirstName

"Miqdad"

LastName

"Kumar"

PKPersonId

1234

PhotoPath

"/UploadFiles/"

Profile

""

Salutation

null

And for the request, don't forget to set dataType:'jsonp' and to add a file in the root directory of your site called crossdomain.xml and containing :

EDIT to take care of Sanjay Kumar POST

So you can set the callback function to be called in the JSONP using jsonpCallback!

$.Ajax({

jsonpCallback : 'your_function_name',

//OR with anonymous function

jsonpCallback : function(data) {

//do stuff

},

...

});

回答7:

When using "jsonp", you would basically be returning data wrapped in a function call, something like

jsonpCallback([{"id":1,"value":"testing"},{"id":2,"value":"test again"}])

where the function/callback name is 'jsonpCallback'.

If you have access to the server, please first verify that the response is in the correct "jsonp" format

For such a response coming from the server, you would need to specify something in the ajax call as well, something like

jsonpCallback: "jsonpCallback", in your ajax call

Please note that the name of the callback does not need to be "jsonpCallback" its just a name picked as an example but it needs to match the name(wrapping) done on the server side.

My first guess to your problem is that the response from the server is not what it should be.

来源:https://stackoverflow.com/questions/16989505/jquery-cross-domain-ajax

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值