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 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名