English 中文(简体)
通过JQuery移动/PhoneGap和ASP.NET MVC 3的跨域服务电话
原标题:Cross-Domain Service Calls via JQuery Mobile/PhoneGap and ASP.NET MVC 3

我正在尝试与 JQuery 移动和电话Gap 建立一个移动应用程序。 这个应用程序将打击与 ASP.NET MVC 3. 合作的后端。 现在, 我正试图让一个基本的 GET/ POST 工作。 我创建了下面的测试页面 。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">

    <link rel="stylesheet" href="resources/css/themes/default/core.css" />    
    <link rel="stylesheet" href="resources/css/themes/default/app.css" />

    <script src="resources/scripts/jquery-1.6.4.min.js" type="text/javascript"></script> 
    <script src="resources/scripts/jquery.mobile-1.1.0.min.js" type="text/javascript"></script>

    <script type="text/javascript">
      function initialize() {
      $.support.cors = true;
          $.mobile.allowCrossDomainPages = true;
      }
    </script>
  </head>

  <body onload="initialize();">
    <div id="testPage" data-role="page">
    <div data-role="header" data-position="fixed">
      <h1>TEST</h1>
    </div>

    <div data-role="content">
      <input id="twitterButton" type="button" value="Test GET via Twitter" onclick="twitterButton_Click();" />
      <input id="getButton" type="button" value="Test GET via MVC 3" onclick="getButton_Click();" />
      <input id="postButton" type="button" value="Test POST via MVC 3" onclick="postButton_Click();" />

      <div id="status"></div>
    </div>

    <div data-role="footer" class="ui-bar" data-position="fixed"> 

    </div>

    <script type="text/javascript">
      function twitterButton_Click() {
        $("#status").html("Testing Twitter...");
          var vm = { q:"1" };
          $.ajax({
      url: "http://search.twitter.com/search.json?q=weekend&rpp=5&include_entities=true&result_type=mixed",
            type: "GET",
            dataType: "jsonp",
            contentType: "application/json",
            success: twitter_Succeeded,
            error: twitter_Failed
          });
        }

        function twitter_Succeeded(result) {
          $("#status").html("Twitter GET Succeeded!");
        }

        function twitter_Failed(p1, p2, p3) {
          $("#status").html("Twitter GET Failed :(");
        }

        function getButton_Click() {
          $("#status").html("Testing Get...");

          var vm = { q:"1" };
          $.ajax({
            url: "https://www.mydomain.com/myService/testGet",
            type: "GET",
            data: vm,
            contentType: "application/json",
            success: get_Succeeded,
            error: get_Failed
          });
        }

        function get_Succeeded(result) {
            $("#status").html("MVC 3 GET Succeeded!");
        }

        function get_Failed(p1, p2, p3) {
            $("#status").html("MVC 3 GET Failed :(");
        }

        function postButton_Click() {
          $("#status").html("Testing POST...");

          var vm = { data:"some test data" };
          $.ajax({
            url: "https://www.mydomain.com/myService/testPost",
            type: "POST",
            data: JSON.stringify(vm),
            contentType: "application/json",
            success: post_Succeeded,
            error: post_Failed
          });       
        }

        function post_Succeeded(result) {
            $("#status").html("MVC 3 POST Succeeded!");
        }

        function post_Failed(p1, p2, p3) {
            $("#status").html("MVC 3 POST Failed :(");
        }
    </script>
</div>
</body>
</html>

当我在视觉工作室内运行此页面时, 我将 AJAX url 调用更改为相对调用。 它们的工作非常完美。 但是, 由于我的目标是在PhoneGap 内运行这个应用程序, 我知道这个页面实际上将作为本地文件运行( < a href="http://jquerymobile.com/demos/1.1.0/docs/pages/phonegap.html" rel=“nofollow noreferrer” > > >http://jquerymotion.com/demos/1.1.0/docs/pages/phonegap.html )。 由于这个原因, 我曾经使用上面的代码, 并在本地机器上创建了测试.html 。

当我尝试运行此代码时, Twitter测试有效。 奇怪的是, 所有三个动作都在互联网探索器中工作。 但是, 当我使用 Chrome 或 FireFox 时, 我的服务器测试无效 。 在 Chrome 中, 我注意到控制台的以下内容 :

XMLHttpRequest cannot load https://www.mydomain.com/myService/testGet?q=1. Origin null is not allowed by Access-Control-Allow-Origin.

XMLHttpRequest cannot load https://www.mydomain.com/myService/testPost. Origin null is not allowed by Access-Control-Allow-Origin.

我读过这个:> 规避同一原产政策的方法 。但是,它们似乎都行不通。我觉得我缺少一些服务器侧面配置。目前,我的测试Get和测试Post的行动看起来如下:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult TestGet(string q)
{
  Response.AppendHeader("Access-Control-Allow-Origin", "*");
  return Json(new { original = q, response=DateTime.UtcNow.Millisecond }, JsonRequestBehavior.AllowGet);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TestPost(string data)
{
  Response.AppendHeader("Access-Control-Allow-Origin", "*");
  return Json(new { status=1, response = DateTime.UtcNow.Millisecond }, JsonRequestBehavior.AllowGet);
}

我觉得我差一点就能拿到这份工作了 我错过什么了?

最佳回答

从一个实际的设备或模拟器中尝试它, 它会有效。 从 FAQ 中 :

The cross-domain security policy does not affect PhoneGap applications. Since the html files are called by webkit with the file:// protocol, the security policy does not apply. (in Android,you may grant android.permission.INTERNET to your app by edit the AndroidManifest.xml)

它总是与Twitter合作,因为它使用 JSONP 回答询问。 您必须开始使用铬或Firefox 的正确方式来告诉它允许 CORS。 对于 Chrome 来说是:

chrome --disable-web-security
问题回答

暂无回答




相关问题
Javascript data store solution using PhoneGap

Does anyone have any experience of storing data in JavaScript across all mobile platforms using PhoneGap? My ideal solution would be to use something like SQLite, but unfortunately SQLite isn t ...

get image from iphone, using phonegap camera api

I m new to Xcode and iPhone apps. I want to select an image from iPhone (camera or library) and send to php via ajax. http://wiki.phonegap.com/iPhone:-Camera-API I m using the phonegap framework, ...

Getting Search Keyboard on iPhone using PhoneGap

I have created a search field on a mobile app i am creating via PhoneGap. I ve tried using with no luck. I also know that i could get around the visual aspect of the input field via CSS & ...

How can I detect a shake gesture in PhoneGap 0.8?

I m using PhoneGap 0.8 and I d like to detect a basic shake gesture. I ve found two relevant snippets: http://groups.google.com/group/phonegap/browse_thread/thread/25178468b8eb9e9f http://phonegap....

How do I fix PhoneGap build errors?

I am trying to build a PhoneGap-based iPhone application, but I keep getting the following two errors: ./build-phonegap.sh: line 6: ./configure: No such file or directory cp: lib/iphone/phonegap-min....

热门标签