2018-07-12 22:26

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

  • cordova
  • post
  • php
  • ajax

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:


    <meta http-equiv="Content-Security-Policy" content="connect-src 'self' data: gap: '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">

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


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

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


    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 ..." . "

    $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)         

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

    echo "success writing to the database 


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.



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

P.S I am using INNODB engine.

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享