简体   繁体   English

无法接收用ajax发布的js数组

[英]cannot receive js array posted with ajax

I am trying to send form data and js array to mysql database. 我正在尝试将表单数据和js数组发送到mysql数据库。 I am having problem with receiving js array into my php. 我在将js数组接收到我的php中遇到问题。 I receive data from form but not the array. 我从表单接收数据,但未从数组接收数据。 I can't find the problem. 我找不到问题。

index.php 的index.php

<!doctype html>
<html lang="en">
<head>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"><!--bootstrap-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script><!--jquery-->
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script><!--angular js-->
<script type="text/javascript" src="assets/js/main.js"></script>

</head>
<body>
<form method="post" action="upload.php">
<!--dynamic form created from javascript-->
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>
</form>
</body>
</html>

javascript -- main.js javascript-main.js

var objArray = []; //Array of questions

function upload(){
            var jsonArray = JSON.stringify(objArray);

            $.ajax({
                type:'post',
                url: 'upload.php',
                data: { jsonData : jsonArray},
                success: function(data){
                   console.log("success!");
               }
            });

    } else {
        console.log("no data javascript!");
    }
}

upload.php upload.php的

<?php

if(($_SERVER['REQUEST_METHOD'] == "POST") && (isset($_POST['submit']))){

    $servername = "......";
    $username = "......";
    $password = "......";
    $dbname = ".....";

    // Create connection
    $conn = new mysqli($servername, $username, $password,$dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    if(!empty($_POST['jsonData'])){
        $json = $_POST['jsonData'];
        var_dump(json_decode($json, true));
        echo "<script type=\"text/javascript\">
              console.log('received data');
        </script>";
     } else {
        echo "data not received";
     }

    $conn->close();

}else {echo "unsecure connection";}
?>

objArray looks like this: objArray看起来像这样:

[{"questionId":1,"questionTypeObj":"single","options":3},{"questionId":2,"questionTypeObj":"single","options":3}]

upload.php outputs "data not received" upload.php输出“未收到数据”

when you click the button your code are going to send 2 requests to the server 当您单击按钮时,您的代码将向服务器发送2个请求

First request-the ajax 第一个请求-Ajax

this ajax request has the parameter you need jsonData : jsonArray and right after that you are going to send another request 此ajax请求具有您需要jsonData : jsonArray的参数,然后您将发送另一个请求

Second request-submitting the form 二次提交申请表

and the form has no jsonData : jsonArray paramter sent with it 并且表单没有jsonData : jsonArray随其发送的jsonData : jsonArray参数

you don't need this ajax at all! 您根本不需要这个ajax!

all you need to do to receive the jsonData : jsonArray paramter is to send it along with the form 接收jsonData : jsonArray所需要做的就是将jsonData : jsonArray参数与表单一起发送

for example: 例如:

change your form to be like this 改变你的形式像这样

<form method="post" action="upload.php">
<input id="jsonData" type="hidden" name="jsonData" value="">
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>
</form>

and change your button function to be like this 然后将您的按钮功能更改为这样

function upload(){
     var jsonArray = JSON.stringify(objArray);
     $('input#jsonData')[0].value=jsonArray ;
}


EDIT : 编辑:

Or if you want upload.php to process the ajax request, and not to response with a whole document then you don't need the form, remove the form from your HTML , and just add submit:Upload to the ajax request 或者,如果您希望upload.php处理ajax请求,而不是对整个文档进行响应,则不需要该表单,将表单从HTML中删除,只需将submit:Upload添加到ajax请求中即可

  data: { jsonData : jsonArray, submit:"Upload" } 

Your output indicates what the problem is: You get to the part where you echo data not received but you are not sending a submit key: $_POST['submit'] is not set when called through ajax. 您的输出表明问题出在哪里:您到达data not received回显data not received但未发送submit键的部分:通过ajax调用时未设置$_POST['submit']

So you are submitting your form the "normal" way and not through ajax. 因此,您是以“常规”方式而不是通过Ajax提交表单的。

This is caused by the fact that you are not cancelling the default submit action of your button. 这是由于您没有取消按钮的默认submit操作引起的。

The best way to solve that (in my opinion...), is to remove the inline javascript - the click handler - and replace your function with: 解决这个问题的最佳方法(我认为...)是删除内联javascript-点击处理程序-并将函数替换为:

$("form").on('submit', function(e) {
    // Cancel the default form submit
    e.preventDefault();

    // The rest of your function
    var jsonArray = JSON.stringify(objArray);
    ...
});

Note that I am catching the form submit event. 请注意,我正在捕获表单提交事件。 You could also replace that with the button click event but that might not work correctly when a visitor uses the enter key in a form field. 您也可以将其替换为按钮单击事件,但是当访问者在表单字段中使用Enter键时,该事件可能无法正常工作。

You shouldn't be doing it this way. 您不应该这样做。 There's no way to guarantee that the javascript will execute before you redirect. 没有任何方法可以确保JavaScript在重定向之前会执行。 In fact, it won't run fast enough, and will just redirect to the next page. 实际上,它的运行速度不够快,只会重定向到下一页。 Try 尝试

<form method="post" action="upload();">

This will get the data to the page, but it won't display it. 这会将数据获取到页面,但不会显示它。 If you want it displayed you should have forms submitting it. 如果要显示它,则应具有提交表单的表单。 If you post with ajax you can also try to catch the response with jquery. 如果您使用ajax发布,也可以尝试使用jquery捕获响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM