jquery - 如何在移动jquery中调用web api方法

标签 jquery cordova

我有 ASP.Net MVC 4 Web API 项目。在此项目的 Controller 中,我创建了返回类型为 HttpResponseMessage 的所有方法。以下是我的 Web API Controller 的代码。

[HttpPost]
public HttpResponseMessage RegisterNewUser(string UserName, string                    AuthToken)
{
    JsonResult objJR = new JsonResult();
    JUser objJU = new JUser();
    HttpResponseMessage response;
    try
    {
        response = Request.CreateResponse(HttpStatusCode.ExpectationFailed,              objJR);
        return response;
    }
    catch (Exception e)
    {
        return CatchError(e.Message);
    }
}

[HttpGet]
public HttpResponseMessage GetUserProfile(int UserID, string AuthToken)
{
    JsonResult objJR = new JsonResult();
    JUser objJU = new JUser();
    HttpResponseMessage response;
    BCUsers objBCUsers = new BCUsers();
    try
    {
        response = Request.CreateResponse(HttpStatusCode.OK, ds);
    }
    return response;
    }
    catch (Exception e)
    {
        return CatchError(e.Message);
    }
}

然后我在phonegap中创建了移动应用程序,我尝试从js文件调用Web API方法,以下是该代码

<script type="text/javascript">
    var CommonURL = "http://localhost/api/common/";

    function GetCoachProfile(UserID,AT) {
        alert('2');
        alert(UserID + AT);
        $.ajax({
            url:  CommonURL + 'GetUserProfile?UserID=' + UserID + '&AuthToken=' + AT,
            type: 'GET',
            datatype: 'json',
            contenttype: "application/json",
            success: function (data) {
                alert('3');
                alert(data);
            },
            error: function(xhr,textStatus,errorThrown) {           
                alert(xhr.responseText);
                alert(textStatus);
                alert(errorThrown);
            }
        });
    }
</script>

GetCoachProfile 函数在 HTML 页面的按钮单击时被调用,我放置在 Web API 方法上的调试点在单击按钮后也会被命中,所有 Web API 方法在 AJAX 调用返回后仍然成功执行它执行错误循环并且不成功,如果有人帮助我,请帮助我,我是phonegap和jQuery的新手。

最佳答案

通过在我的 Web api 项目的 web.config 文件中添加以下代码行来解决,该问题是由于跨平台造成的。

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

关于jquery - 如何在移动jquery中调用web api方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30617754/

相关文章:

javascript - Typed.js 不工作

jquery - 获取所选选项的类名

ios - 从 Cordova iOS 中的委托(delegate)返回数据

javascript - 从没有名称和 ID 值的元素分离 CK 编辑器

javascript - 当前父元素的子元素选择器

jquery - 如何让文本/对象保留在 div 元素中? (有 div "stretch"所以所有的内容都会留在里面?)

ios - 无法使用 Cordova 模拟 ios

javascript - 新的phonegap项目失败并出现TypeError : undefined is not a function on line 1

android - PhoneGap 3.3.0 又名 Cordova 与 PhoneGap 3.2.0

cordova - 新的 ios6 架构错误 : file is universal (3 slices) but does not contain a(n) arm7vs slice