Home  >  Q&A  >  body text

javascript - 添加多条数据组织为一个对象并传给php,php如何接收参数并解析为正常数据并插入到表中?

做了个增删改查的表,新增的数据有多条,我现在都是在URL中以 ? 后加参数的形式传给php,然后,php用$_GET['']接收传过来的参数。这是可以实现新增数据的方法,我想问的是,如果新增数据特别多的情况下,php怎么接收解析传过来的参数呢?
下面是我的代码?
php:

//新增方法
    function add_row(){
        /*获取从客户端传过来的数据*/
        $userName = $_GET['user_name'];
        $userAge = $_GET['user_age'];
        $userSex = $_GET['user_sex'];
        
        $sql = "INSERT INTO t_users (user_name,user_age,user_sex) VALUES ('$userName','$userAge','$userSex')";
        if(query_sql($sql)){
            echo "ok!";
        }else{
            echo "新增成功!";
        }
    }

    function query_sql(){
        $mysqli = new mysqli("127.0.0.1", "root", "root", "crud");
        $sqls = func_get_args();
        foreach($sqls as $s){
            $query = $mysqli->query($s);
        }
        $mysqli->close();
        return $query;
    }

js:

$(function() {
                
    $('#save').click(function(){
        addData();
    });
});
function addData(){
    var userName = $('#userName').val();
    var userAge = $("#userAge").val();
    var userSex = $('#user-sex').val() == '0' ? '男' : '女';
                
    var addUrl = "./php/data.php?action=add_row&user_name=" + userName + "&user_age=" + userAge + "&user_sex=" + userSex;
                
                $.ajax({
                    type:"post",
                    url:addUrl,
                    dataType:'json',
                    contentType:'application/json;charset=utf-8',
                    success:function(data){
                        console.log("success");
                    },
                    error:function(data){
                        console.log("data");
                        //添加成功后隐蒧modal框并重新加载页面
                        setTimeout(function(){
                            $('#exampleModal').modal('hide');
                        },500);
                        setTimeout(function(){
                            //新增成功后,重新加载数据
                            searchData();
                        },700);
                    }
                });
            }

上面写的可能不太明白,我想要表达的意思是,如果php的代码不变,变的仅是js新增这个方法中的数据组织,如果有多条数据需要新增,我把这多条数据组织为一个对象并把这个对象给解析为一个字符串传给php。那么这个php如何解析数据呢?

function addData(){
                var userName = $('#userName').val();
                var userAge = $("#userAge").val();
                var userSex = $('#user-sex').val() == '0' ? '男' : '女';
                
                /*var addUrl = "./php/data.php?action=add_row&user_name=" + userName + "&user_age=" + userAge + "&user_sex=" + userSex;*/
                var addUrl = "./php/data.php?action=add_row";
                var addData = {
                    'user_name':userName,
                    'user_age':userAge,
                    'user_sex':userSex
                };
                
                var jsonData = JSON.stringify(addData);
                
                $.ajax({
                    type:"post",
                    url:addUrl,
                    data:jsonData,//传给php
                    dataType:'json',
                    contentType:'application/json;charset=utf-8',
                    success:function(data){
                        console.log("success");
                    },
                    error:function(data){
                        console.log("data");
                        //添加成功后隐蒧modal框并重新加载页面
                        setTimeout(function(){
                            $('#exampleModal').modal('hide');
                        },500);
                        setTimeout(function(){
                            searchData();
                        },700);
                    }
                });
            }

求大侠解答一下,非常感谢!

阿神阿神2734 days ago528

reply all(7)I'll reply

  • 黄舟

    黄舟2017-05-16 13:01:35

    For new operations, use the POST method. Ajax sends json(data:{a:'',b:'',c:''}) data, and after php receives it, jsondecode($_POST['data'])

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-16 13:01:35

    Put all parameters in a json number and pass it to the background: {'username': xxx, 'age': xxx}, according to the comments and logic of your code, those codes should be written in success instead of error

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:01:35

    I don’t understand what you are saying. Ajax returns it directly after receiving it, and your default is dataType:'json', which means that as long as the data returned in php is not in json format, an error will be reported. Take a look at the above //echo "Add successfully!"; This will directly cause you to report an ajax error.

     if(query_sql($sql)){
                //echo "ok!";
                $r['code']=0;
                $r['msg']='ok!';
            }else{
                //echo "新增成功!";
                $r['code']=1;
                $r['msg']='新增成功!';
            }
            exit(json_encode($r));

    reply
    0
  • PHPz

    PHPz2017-05-16 13:01:35

    The conditions for success are (xmlHttp.readyState == 4) && (xmlHttp.status == 200)
    See if the status code returned by the address you requested is 200?

    If there are many parameters, you can directly assign $_GET to a variable, because $_GET is an array.

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-16 13:01:35

    Receive the $_GET array and then traverse

    reply
    0
  • 为情所困

    为情所困2017-05-16 13:01:35

    Use POST

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-16 13:01:35

    1. The ajax submission method is teyp: "post", but the parameter received by php is $_GET
    2. The data format received by ajax is dataType: 'json', but the result returned by php is text.
    3.ajax request content format contentType:'application/json;charset=utf-8', the requested data should be a json string. If you use php to receive it in the background, you can use $data = file_get_contents("php://input "); json_decode($data, true), which is the request parameter. (Four Common ContentTypes in HttpRequest (transfer))
    4.sql needs to be protected from injection

    reply
    0
  • Cancelreply