ajax成功函数从php

时间:2015-09-11 11:20:12

标签: php ajax callback

我无法使用ajax从php脚本接收数据。我有一个表单将信息发送到PHP脚本。这只是一个考验。如果它有效,我想从数据库接收信息。

    $('.search-member-submit-btn').click(function () {
    var firstname = $("#search-member-firstname").val();
    var lastname = $("#search-member-lasttname").val();

    $.ajax({//AJAX request
        type: "POST",
        url: "/website/include/process/send_membersearchrequest_process.php",
        async: true,
        data: {firstname: firstname, lastname: lastname},
        success: function (data) {
            alert(data);
            $(".search-member-result-address").html(data);
        },
    });

});

HTML:

<div class="col-md-3">
     <div class="search-member-result-container">
          <address class="search-member-result-address">

          </address>
      </div>
</div>
<div class="search-member-form">
     <input class="search-member-input" id="search-member-lastname" placeholder="Name">
     <input class="search-member-input" id="search-member-firstname" placeholder="Vorname">
     <div class="search-member-submit-btn">suchen</div>
</div>

PHP

<?php 
    $lastname = $_POST['lastname'];
    echo $lastname;
?>

2 个答案:

答案 0 :(得分:0)

我宁愿这样做:

的Javascript

$.ajax({//AJAX request
        type: "POST",
        url: "/website/include/process/send_membersearchrequest_process.php",
        async: true,
        dataType:'json'
        data: {"firstname": firstname, "lastname": lastname},
        success: function (data) {
            alert(data.result);
            $(".search-member-result-address").html(data.result);
        },
    });

PHP

<?php 
      $lastname = $_POST['lastname'];
      $res = array("result" => $lastname);
      echo json_encode($res);
?>

像这样,你将一个json发送到你的服务器并获得一个json作为回报。

答案 1 :(得分:0)

添加响应类型:

 $.ajax({//AJAX request
        type: "post",
        url: "/website/include/process/send_membersearchrequest_process.php",
        async: true,
        data: {firstname: firstname, lastname: lastname},
        dataType: 'json', // You have to add this line
        success: function (data) {
            alert(data.response);
            $(".search-member-result-address").html(data.response);
        },
    });

和您的PHP文件:

<?php 
$lastname = $_POST['lastname'];
echo json_encode(array('response' => $lastname));
exit();
?>