iOS上的Web服务AJAX Post获得错误400

时间:2013-11-05 14:48:26

标签: javascript php ios ajax html5

后台:我想创建一个可以随意更改外形的混合应用程序。这需要应用程序嵌入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代码中做错了什么?

1 个答案:

答案 0 :(得分:0)

我通过更改网址解决了这个问题。 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.如果有人可以评论,那将是伟大的!谢谢!