javascript - Add multiple pieces of data organized into an object and pass it to php. How does php receive the parameters and parse them into normal data and insert them into the table?
阿神
阿神 2017-05-16 12:59:35
0
7
546

I made a table for adding, deleting, modifying, and querying. There are many new pieces of data. I now use ? in the URL. Pass it to php in the form of appended parameters, and then php uses $_GET[''] to receive the passed parameters. This is a way to add new data. What I want to ask is, if there is a lot of new data, how does PHP receive the parameters passed by the parsing?
Here is my code?
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);
                    }
                });
            }

You may not understand what is written above. What I want to express is that if the PHP code remains unchanged, all that changes is the new data organization in this method of JS. If there are multiple pieces of data that need to be updated, By the way, I organized these multiple pieces of data into an object and parsed the object into a string and passed it to php. So how does this php parse the data?

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);
                    }
                });
            }

Please give me some answers, thank you very much!

阿神
阿神

闭关修行中......

reply all(7)
黄舟

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

phpcn_u1582

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

Ty80

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));
PHPzhong

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.

我想大声告诉你

Receive the $_GET array and then traverse

为情所困

Use POST

漂亮男人

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template