0
$.ajax({

      url: 'https://XXXXX.desktop.XXXX.com:9011/iws-merchant/XXXXX.htm',
      dataType: "jsonp",
      success: function (response) {
       str=response;

      },
      error: function( response ) {
          alert( "ERROR:  " + JSON.stringify );
       }
   });

它总是在错误块中。我正在对不同的 PORT(相同域)进行 AJAX 调用。

但是当我尝试在新标签中点击相同的 URL 时。我能够看到响应。

任何帮助都将受到高度赞赏。

4

2 回答 2

3

you can use JSONP as Gaurav Agrawal suggested OR you can enable the Access-Control-Allow-Origin for the site who receives ajax request.

Ajax works like this: Same domain but different port = different domain

if you are using asp.net on your ajax target server you can enable access control adding this in web.config:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
<system.webServer>

and do yourself a favor and replace "*" with your site url!

in some situation you can need even those keys, just google every function before adding it!

<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Expose-Headers" value="*"/>
于 2013-03-11T11:24:11.143 回答
2

您不能使用 JSON 进行跨域 AJAX 调用。您需要使用 JSONP。因此,不要从控制器操作返回常规 JsonResult,而是编写一个自定义操作结果,它将 JSON 包装在作为参数传递的回调中:

public class JsonpResult : ActionResult
{
    private readonly object _obj;

    public JsonpResult(object obj)
    {
        _obj = obj;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var serializer = new JavaScriptSerializer();
        var callbackname = context.HttpContext.Request["callback"];
        var jsonp = string.Format("{0}({1})", callbackname, serializer.Serialize(_obj));
        var response = context.HttpContext.Response;
        response.ContentType = "application/json";
        response.Write(jsonp);
    }
}

然后让您的控制器操作返回此自定义操作结果:

public ActionResult SomeAction()
{
    var result = new[]
    {
        new { Id = 1, Name = "item 1" },
        new { Id = 2, Name = "item 2" },
        new { Id = 3, Name = "item 3" },
    };
    return new JsonpResult(balances);
}

现在您可以跨域使用此操作:

var url = "http://example.com/SomeController/SomeAction/";
$.getJSON(url + '?callback=?', function (data) {
    alert(data);
});
于 2013-03-11T11:17:27.853 回答