javascript - 为什么 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 的响应中没有得到那个回显的字符串。它改为发送一个对象。我正在尝试用这个数据库制作其他项目,但我有同样的问题。
解决方案
请参阅文档。您正在使用complete
回调,它接收jqXHR
对象作为其第一个参数。
相反,如果要使用返回的数据,则要使用success
(two c
s, note),而不是。接收数据作为其第一个参数。(您也可以使用删除正在进行的消息等)complete
success
complete
例如:
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
}
推荐阅读
- android - 添加firestore后错误无法访问zza
- java - 带有新的初始化类变量的 Mockito InjectMocks
- python - tf.argmax() 用于多个索引 Tensorflow
- ios - 当用户未连接到互联网时,如何禁用所有 UIViewControllers 的用户交互?
- android - Android Studio Kotlin 自动完成符号
- tomcat7 - java.lang.OutOfMemoryError: 在 Spring Data MongoDB 中 MongoTemplate.save(Object objectToSave) 时出现 PermGen 空间错误
- java - 如何使用 ModelMapper 进行深度继承对象?
- python - 堆叠多个 Landsat 图像
- javascript - simplecart js 多视图功能
- bash - 在 docker 容器中编辑 war 文件中的文件