1

我想$.ajax从外部 ASP.NET MVC 站点(在本例中 - 从我的站点)检索一些数据。下面的代码给了我一个404 Not Found error(当然url是有效的。

但是,如果我将 url 从更改url: 'http://myurl.com/Home/GetMyCode/?id=mycode'url: 'http://localhost:123/Home/GetMyCode/?id=mycode'一切都很好。那么,如何解决呢?

 $.ajax({
        url: 'http://myurl.com/Home/GetMyCode/?id=mycode',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        crossDomain: true,
        success: function (res) {
            ...
        },
        error: function (jqXHR, textStatus, errorThrown) {
            ...
        }
    });


    [HttpPost]
    public JsonResult GetMyCode(string id)
    {
        try 
        {
            return Json(new { result = "ok", resultData = "OK") });
        }
        catch (Exception e)
        {
            return Json(new { result = "error", resultData = "An error occured" });
        }            
    }
4

4 回答 4

2

处理跨域 Ajax 调用的两种方法:

JSONP:跨域访问的当前标准

JSONP 是一些网站用来公开其内容的一种约定,这种方式使调用者更容易通过脚本使用数据,甚至是来自外部域的数据。诀窍在于让网站返回一些 JSON 内容,而不是作为纯字符串,而是包装在脚本函数调用中。更多细节..

跨域资源共享 (CORS)

要在尚不支持 cors 但允许跨域 XHR 请求(windows gadget 等)的环境中启用跨域请求,请设置 $.support.cors = true; You just tell jQuery that you are in an environment where Cross-Domain XHR requests are possible。

于 2012-12-12T03:26:15.940 回答
1

为了跨域检索数据,您可能需要使用“jsonp”

于 2012-12-12T03:11:05.287 回答
0

看起来这可能是一个DNS问题。您可以访问:http ://myurl.com吗?

您尝试访问的 .com 域是否可公开访问?或者它是到本地主机的环回?

于 2012-12-11T22:16:50.147 回答
0

该教程对我有用,我必须在我的 MVC 项目中实现 JSONP 处理。 http://www.codeguru.com/csharp/.net/net_asp/using-jsonp-in-asp.net-mvc.htm

于 2012-12-12T15:12:52.517 回答