当我尝试从Ajax POST时,PHP未定义的索引数据

时间:2017-06-05 16:17:49

标签: javascript php jquery ajax

我正在尝试使用Ajax POST请求更新mysql数据库到php文件,但是我收到以下错误:

Notice: Undefined index: data in C:\xampp\htdocs\php\php\post.php on line 2

Notice: Undefined index: data in C:\xampp\htdocs\php\php\post.php on line 2
{"d":true}{"d":true}

这是我的Ajax代码:

$('#addbut').click(function()
    {
        console.log($("#firstteam").val());
        console.log($("#score1").val());
        console.log($("#score2").val());
        console.log($("#secondteam").val());

        var data = {
        firstteam:$("#firstteam").val(),
        secondteam:$("#secondteam").val(),
        score1:$("#score1").val(),
        score2:$("#score2").val()}

        $("#firstteam").val('');
        $("#secondteam").val('');
        $("#score1").val('');
        $("#score2").val('');

        $.ajax({
            type: "POST",
            url: "php/post.php",
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType:'json',

            //if received a response from the server
            success: function(response) 
            {
                 var res = response.d;
                 if (res == true)
                 {
                     $("#error").html("<div><b>Success!</b></div>"+response);
                     updateTable();
                 }
                 //display error message
                 else {
                     $("#error").html("<div><b>Information is Invalid!</b></div>"+response);
                 }
            },

            //If there was no resonse from the server
            error: function(jqXHR, textStatus, errorThrown)
            {
                 console.log("Something really bad happened " + textStatus);
                 $("#error").html(jqXHR.responseText);
            }
        });  

    });

这里是我的PHP代码:

<?php
    $data = $_POST['data'] or $_REQUEST['data'];
    $js = json_decode($data,true);
    $t1 = $js['firstteam'];
    $t2 = $js['secondteam'];
    $s1 = $js['score1'];
    $s2 = $js['score2'];

    updateFunction($t1,$s1,$s2);
    updateFunction($t2,$s2,$s1);



    function updateFunction($name, $s1, $s2) 
    {
        $conn = new mysqli("localhost:3306","root","","leagues"); 
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        if ($s1 > $s2)
            $sql = "UPDATE league SET playedgames=playedgames + 1,wongames = wongames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."', points = points + 3 WHERE teams='".$name."'";
        else
            if ($s1 == $s2)
                $sql = "UPDATE league SET playedgames=playedgames + 1,tiegames = tiegames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."', points = points + 1 WHERE teams='".$name."'";
            else
                if ($s1 < $s2)
                    $sql = "UPDATE league SET playedgames=playedgames + 1,lostgames = lostgames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."' WHERE teams='".$name."'";

        if ($conn->query($sql) === TRUE) 
        {
            $response = json_encode(array('d' => true)); 
            echo $response;
        }
        $conn->close();
    }
?>

我尝试了一些建议,但我不知道为什么我的PHP代码没有正确解析数据。我的Ajax函数中的Console.log打印出我想要的内容。

以下是我的调试器显示的内容: enter image description here

1 个答案:

答案 0 :(得分:2)

它不起作用,因为放

>>> import pandas as pd
>>> s = pd.Series(['abc', 'def', 'ghi'])
>>> s.str.contains('a')
0     True
1    False
2    False
dtype: bool
>>> s.eq('a')  # looking for an identical match
0    False
1    False
2    False
dtype: bool

您只需将原始格式的字符串(Uri file = Uri.fromFile(new File("your_image_path")); StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment()); uploadTask = riversRef.putFile(file); // Register observers to listen for when the download is done or if it fails uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle unsuccessful uploads } }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL. Uri downloadUrl = taskSnapshot.getDownloadUrl(); } }); )放入请求正文中即可。 因此,没有名为$.ajax({ ... data: '{"key":"value"}', ...}); 的表单参数。

要从正文使用中检索此原始数据:

{"key":"value"}

而不是

data