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

使用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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog