0

背景:我想创建一个可以随意改变外形的混合应用程序。这需要应用程序嵌入 webView。这个 webView 也应该能够与后端服务器对话。我使用非常小的 php 代码在我的 Mac (localhost) 上托管后端。

API

<?php
  function getStatusCodeMessage($status)
        {
            // these could be stored in a .ini file and loaded
            // via parse_ini_file()... however, this will suffice
            // for an example
            $codes = Array(
                           100 => 'Continue',
                           101 => 'Switching Protocols',
                           200 => 'OK',
                           201 => 'Created',
                           202 => 'Accepted',
                           203 => 'Non-Authoritative Information',
                           204 => 'No Content',
                           205 => 'Reset Content',
                           206 => 'Partial Content',
                           300 => 'Multiple Choices',
                           301 => 'Moved Permanently',
                           302 => 'Found',
                           303 => 'See Other',
                           304 => 'Not Modified',
                           305 => 'Use Proxy',
                           306 => '(Unused)',
                           307 => 'Temporary Redirect',
                           400 => 'Bad Request',
                           401 => 'Unauthorized',
                           402 => 'Payment Required',
                           403 => 'Forbidden',
                           404 => 'Not Found',
                           405 => 'Method Not Allowed',
                           406 => 'Not Acceptable',
                           407 => 'Proxy Authentication Required',
                           408 => 'Request Timeout',
                           409 => 'Conflict',
                           410 => 'Gone',
                           411 => 'Length Required',
                           412 => 'Precondition Failed',
                           413 => 'Request Entity Too Large',
                           414 => 'Request-URI Too Long',
                           415 => 'Unsupported Media Type',
                           416 => 'Requested Range Not Satisfiable',
                           417 => 'Expectation Failed',
                           500 => 'Internal Server Error',
                           501 => 'Not Implemented',
                           502 => 'Bad Gateway',
                           503 => 'Service Unavailable',
                           504 => 'Gateway Timeout',
                           505 => 'HTTP Version Not Supported'
                           );

            return (isset($codes[$status])) ? $codes[$status] : '';
        }

        // Helper method to send a HTTP response code/message
        // function sendResponse($status = 200, $body = '')
        function sendResponse($status = 200, $body = '', $content_type = 'text/html')
        {
            $status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
            header($status_header);
            header('Content-type: ' . $content_type);
            echo $body;
        }

    class testPostApi {
        function __construct() {
        }

        function __destruct() {
        }
        // Helper method to get a string description for an HTTP status code
        // From http://www.gen-x-design.com/archives/create-a-rest-api-with-php/



        // Main method to redeem a code
        function testPost(){
            // check for required parameters
            if (isset($_POST["name"]) && isset($_POST["age"])){
                $name = $_POST["name"];
                $age = $_POST["age"];

                 // Return code, encoded with JSON
                $result = array(
                                "name" => $name,
                                "age" => $age                               
                                 );
                sendResponse(200, json_encode($result));
                return true;
            }
            sendResponse(400, 'Invalid request');
            return false;
        }
    }

    // This is the first thing that gets called when this page is loaded
    // Creates a new instance of the RedeemAPI class and calls the redeem method
    $api = new testPostApi;
    $api->testPost();

    ?>

然后在 iOS 模拟器上运行一个小的 HTML5 脚本

    <!DOCTYPE HTML>
<html>
    <head>
        <meta name="viewport" content="initial-scale=1, user-scalable=no">
    </head>

    <body>

        <button onclick="submit()">Submit</button>

        <script>
            function submit()
            {
                var xmlhttp;
                if (window.XMLHttpRequest)
                {// code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp=new XMLHttpRequest();
                }
                else
                {// code for IE6, IE5
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }

                xmlhttp.onreadystatechange=function()
                {
                    alert(xmlhttp.status);

                    /*if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {

                    }*/
                }
                var params = "name=john&age=40";

                xmlhttp.open("POST","http://localhost/testPost",true);

                xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xmlhttp.setRequestHeader("Content-length", params.length);
                xmlhttp.setRequestHeader("Connection", "close");

                xmlhttp.send(params);
            }
        </script>
    </body>
</html>

问题:我使用终端命令测试curl -F "name=john" -F "age=40" http://localhost/testPost/并返回{"name":"john","age":"40"}。从而证明后端工作正常。但是当我使用模拟器按钮时,警报会显示代码 400(或未设置帖子值时我想要的任何内容)错误请求(状态 2、3、4 的 3 次)。

附加信息:使用 html 文件时,chrome 和 firefox 都返回代码 0。奇怪的是,Safari 实际上提供了与 iPhone 模拟器相同的代码。

问题:我在 AJAX/HTML5 代码中做错了什么?

4

1 回答 1

0

我通过更改 URL 解决了它。testPost是一个文件夹,里面有 index.php。我不知道它需要添加到 URL 中。我变了:

xmlhttp.open("POST","http://localhost/testPost",true);

xmlhttp.open("POST","http://localhost/testPost/index.php",true);

你知道吗,它有效!我用 Safari 进行了测试,它工作得很好,就像 iphone safari 一样。但由于某种原因,Firefox 和 chrome 仍然显示代码 0。如果有人可以对此发表评论,那就太好了!谢谢!

于 2013-11-05T15:47:19.943 回答