weixin_33709590 2016-12-08 18:11 采纳率: 0%
浏览 25

来自PHP文件的AJAX发布数据

I have a php file to validate a form with data that need to get sent through ajax. The data that I receive back from the php file is unchanged, how can I receive the correct data? main.js

$("#PersonForm").submit(function()
{ 
  var data = $("form").serializeArray();
  $.ajax({
    type:"post",
    url:"main.php",
    act: 'validate',
    datatype:"json",
    data:data,
    function(data){
      console.log(data);
  }});

  return false;
});

main.php

else if ($_REQUEST['act'] == 'validate')
{
    $validateData = array();

    if (preg_match("[A-Za-z]{3,20}$/",$_REQUEST['name'])){
        $validateData['name'] = 1;
    }else{
        $validateData['name'] = 0;
    }

    echo json_encode($validateData);

The data that originally gets sent in the data array is name:Bob
The expected return is 1 or 0 but I recieve name:Bob back.

  • 写回答

1条回答 默认 最新

  • csdn产品小助手 2016-12-08 18:21
    关注

    Ok, the issue is you have to actually pass that in the data. You are doing this:

    $.ajax({
        type:"post",
        url:"main.php",
        act: 'validate', // <--- THIS IS WRONG
        datatype:"json",
        data:data,       // <--- IT SHOULD BE IN THIS
        function(data){
          console.log(data);
        }
    });
    

    It has to be in your data variable to be passed. You are using it as an option to the jQuery ajax() method, which doesn't work.

    var data = $("form").serializeArray();
    data.push({name: 'act', value: 'validate'});
    // Then make ajax call here
    

    After serializing your form data, you can add that on as an additional value.

    评论

报告相同问题?