dongma1666
2018-07-12 22:26
浏览 244
已采纳

使用AJAX的Cordova POST请求不止一次写入数据库

I am messing around with Cordova, trying to write/read results from/to a remote database with POST requests. The problem I have is that a single AJAX POST request seems to write two times to the database instead of once.

bellow is my code:

HTML

    <head>
    <meta http-equiv="Content-Security-Policy" content="connect-src http://example.com/ 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    </head>

    <body>
    [plain html]
    <script src="js/ajaxCall.js"></script>
    </body>

ajaxCall.js

    var c2JSON = "username":"dummyUser","password":"predictable","load":123};

    $.ajax({
    type: 'POST',
    url: 'example.com/writeToDB.php',
    data: JSON.stringify(c2JSON),
    success: function(data) {console.log('results: ' + data);},
    error: function (jqXHR, exception) {console.log(jqXHR.status + ' --- ' + exception);},
    contentType: "application/json;",
    });

writeToDB.php

    <?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Access-Control-Allow-Methods: POST');

    # Get JSON as a string
    $json_str = file_get_contents('php://input');
    # Get as an object
    $json_obj = json_decode($json_str, false);
    echo "dumping received data as object ..." . "
";
    var_dump($json_obj);

    $userName = $json_obj->username;
    $password = $json_obj->password;
    echo "userName: " . var_dump($userName);
    echo "password: " . var_dump($password);

    $con = mysqli_connect("url","usr","pswd","myDB");
    mysqli_query($con,"SET NAMES 'utf8'");
    mysqli_query($con,"SET CHARACTER SET 'utf8'");

    $query = "INSERT INTO User(Username, Password)         
    VALUES('$userName','$password')";

    if(!mysqli_query($con, $query))
    {
    die('Error: ' . mysqli_error($con));
    echo "error running query";
    }

    echo "success writing to the database 
";

    mysqli_close($con);
    ?>

The result in the database is an empty row, followed by what I intended to writeenter image description here

(first column is the primary key id).

In chrome, I see the following:

enter image description here

The printing order seems a bit off as you can see.

I suspected it had something to do with CORS, where the AJAX call was requesting the PHP file twice, once during the preflight and once during the actual call, but if that was the case I would have seen twice the output which is not what is happening here.

Adding

    if(!empty($userName)&&!empty($password))

before running the query solves the problem, but I would like to know why it happens.

P.S I am using INNODB engine.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douhan9467 2018-07-13 22:07
    已采纳

    So, what is happening, since it is a post request to another domain a CORS preflight is triggered anyways, hence the extra call from my jquery file on top of my own call.

    What I did to control the flow of the calls is the following code in my php code:

    // Allow from any origin for testing purposes
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: *");
    }
    
    // this is the preflight control block
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
        exit(0);
    }
    
     //this is true after the preflight
     if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    //db insertion
    exit(0);
     }
    

    My previous code had no way to find which part of the call to the php file was a preflight request or the actual POST request and the db insertion code was running anyways. With the above code I can do the actual stuff I want only during the "actual" POST request.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题