首页 > 解决方案 > 为什么 Ajax 在响应中发送对象?

问题描述

我在 php 中有一个非常简单的脚本,它假设向 ajax 发送请求并返回我放入 .php 文件中的字符串,但是当请求响应时,它发送一个对象而不是字符串。我不知道为什么会这样,因为我以前已经以同样的方式这样做并且工作正常。

这是发送请求的表格

<form method="POST" id="personForm">
    <div class="form-group col-md-6">
        <label for="NameInput">Name</label>
        <input type="text" name="name" class="form-control" id="NameInput">
    </div>
    <div class="form-group col-md-6">
        <label for="lNameInput">Last Name</label>
        <input type="text" name="lastname" class="form-control" id="lNameInput">
    </div>
    <input type="button" name="Send" class="btn btn-info" onclick="ajaxRequest($('#NameInput').val(), $('#lNameInput').val())" value="Send">
</form>
<hr>
<div id="result">

</div>

这是发送 ajax 请求的脚本

function ajaxRequest(name, lastn) {

   var params = {
      "name" : name,
      "lastn" : lastn
      };

      $.ajax({
        url: './process/resquestAjax.php',
        method: 'POST',
        data: params,
        beforeSend: function() {

          $('#result').html('<p>Procesando Peticion...</p>');

        },
        complete: function(completeResult) {

          $('#result').html(completeResult);

        },
        sucess: function(successResult) {

        },
        error: function(jqXHR,estado,error){
          alert('There was an error!: '+estado+' name-> '+error+' otro-> '+jqXHR);
          alert("Please contact support ias soon as posible...!");
        }
       }); // End Ajax Call
}

而php文件就是这个

$nombre   = $_POST['name'];
$apellido = $_POST['lastname'];

echo "¡Hello! your name is : ". $nombre ." and your last name: ". $apellido;

我不知道为什么我在 ajax 的响应中没有得到那个回显的字符串。它改为发送一个对象。我正在尝试用这个数据库制作其他项目,但我有同样的问题。

标签: javascriptphpjqueryhtmlajax

解决方案


请参阅文档。您正在使用complete回调,它接收jqXHR对象作为其第一个参数。

相反,如果要使用返回的数据,则要使用success(two cs, note),而不是。接收数据作为其第一个参数。(您也可以使用删除正在进行的消息等)completesuccesscomplete

例如:

function ajaxRequest(name, lastn) {
    var params = {
        "name" : name,
        "lastn" : lastn
    };

    $.ajax({
        url: './process/resquestAjax.php',
        method: 'POST',
        data: params,
        beforeSend: function() {
            $('#result').html('<p>Procesando Peticion...</p>');
        },
        complete: function(completeResult) {
            // If you wanted to do something whether the request
            // succeeded or failed, you'd do it here. Otherwise,
            // remove this handler.
        },
        success: function(successResult) {
            $('#result').html(successResult);
        },
        error: function(jqXHR,estado,error){
            alert('There was an error!: '+estado+' name-> '+error+' otro-> '+jqXHR);
            alert("Please contact support ias soon as posible...!");
        }
    }); // End Ajax Call
}

推荐阅读