小编典典

从AJAX调用到PHP检索POST数据

ajax

三天过去了,但仍然无法解决问题。当发送JSON数据时,对我的js文件的此AJAX调用似乎可以正常工作:

 var _lname = $('#ptLastName').val();
 var _fname = $('#ptFirstName').val();
 var _mname = $('#ptMiddleName').val();
 var _gender = $('#ptGender').val();
 var _bday = $('input[name="birthdate"]').val(); // $('#ptBirthDate').val();
 var _ssn = $('#ptSSN').val();

 $.ajax({
          type: "POST",
          url: ".././CheckPerson.php",
          data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function (response) {
          var res = response.d;
          if (res == true) {
               jAlert('Person Name already exists!', 'Error');
               return;
          } 
})

但在我的PHP文件中:

$lastname = json_decode($_POST['lastName']);
$firstname = json_decode($_POST['firstName']);
$middlename = json_decode($_POST['middleName']);
$response = array();

mysql_connect ("*****", "****") or die ('Error: ' . mysql_error());
mysql_select_db ("********");

$query = "SELECT Lastname, Firstname, MiddleName FROM tbl_people WHERE Lastname = '$lastname' || Firstname = '$firstname' || MiddleName = '$middlename'";

$result = mysql_query($query);

$row = mysql_fetch_array($result);

    if ($row) {     
        $response = json_encode(array('d' => true, 'test' => $lastname)); 
    }
    else { 
    $response = json_encode(array('d' => false, 'test' => $lastname));
    }
echo $response;
print json_encode($_POST);

Firebug控制台出现一些错误:

<br />
<b>Notice</b>:  Undefined index: lastName in <b>C:\xampp\htdocs\..\CheckPerson.php</b> on line <b>2</b><br />
<br />
<b>Notice</b>:  Undefined index: firstName in <b>C:\xampp\htdocs\..\CheckPerson.php</b> on line <b>3</b><br />
<br />
<b>Notice</b>:  Undefined index: middleName in <b>C:\xampp\htdocs\..\CheckPerson.php</b> on line <b>4</b><br />
{"d":false,"test":null}[]

我相信这json_decode()在我的php文件中工作正常,但是$_POST['']无法从w / c变量声明的ajax调用中识别出我发布的数据:

data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",

我相信我对我的代码做得正确,似乎我在这里阅读了许多问题,做了他们说的话,但不知道为什么会发生错误。您是否遇到任何问题/错误?请告诉我。


阅读 228

收藏
2020-07-26

共1个答案

小编典典

您可以使用Firebug控制台查看ajax请求数据吗?

您无法从$ _POST获得姓氏,名字。它在json字符串中。首先,您必须使用

 $data = $_POST['data'] or $_REQUEST['data']

Then, decode the $data using json_deocde and access your attributes.

json_decode($data);
2020-07-26