我需要创建一个脚本,从表单中获取数据,将其发送到服务器(它上面有一些恶魔般的C#程序,这不是我的工作......),服务器解析字符串并用4个字符串回复我(是的,他们是西班牙语):'pendiente','verificada','rechazada',最后'错误' 现在,我必须得到响应并正确显示正确的消息(隐藏内联html)。 所有这些程序都不应该“刷新”实际的页面,所以我正在使用AJAX。
请记住我是新手:)我已经学会了Jquery这个任务, 我不得不说我对此非常满意。
我真的不知道如何使用Jquery处理或“操纵”该请求...我想到了如何将数据发送到服务器,但我认为我处理错误的响应。
在这种情况下我调整了脚本,每个不同的响应都应该有自己的边框颜色,我使用条件(肯定是错的)将CSS clases添加到#ajax div。
所以,它可能有愚蠢的错误......
$(document).ready(function () {
$('#enviar').click(function (event) {
event.preventDefault(); //avoid page refresh
var consulta = $('#string').val();
$("#normal").text(consulta);
//Start AJAX!
$.ajax({
async: true,
cache: false,
type: 'post',
url: 'http://184.22.97.218:8081/chequeostatusdonation', //la del servr
data: {
html: consulta
},
dataType: 'html',
beforeSend: function () {
console.log('Sending...');
},
success: function (data) {
console.log('Just sent -'+data+'- with success dooh');
$('#ajax').html(data);
//start conditional
if (data == pendiente) {
$("#ajax").addClass(pendiente);
} else if (data == verificada) {
$("#ajax").addClass(verificada);
} else if (data == rechazada) {
$("#ajax").addClass(rechazada);
} else {
$("#ajax").html('<h1>error</h1>');
}
//end condicional
},
complete: function () {
console.log('Listo el pollo');
}
});
});
});
以下是 JSFiddle
编辑:现在,我刚刚找到了这两个链接 learn.jquery.com/code-organization/concepts/ learn.jquery.com/code-organization/beware-anonymous-functions /
拧我的代码! :d
答案 0 :(得分:1)
Async默认为“true”,因此您无需在代码中提及。
您包含了指向服务器的链接(在URL字段中),但您尝试打开的文件是什么?您需要包含从(文件/脚本)获取数据的路径。要使Ajax工作,您需要遵守“相同的原始策略”,这样您就可以插入文件/脚本的相对路径。
您的通话响应是否总是一个短字符串,其中一个关键字('pendiente','verificada','rechazada'或'错误)?在这种情况下,我会建议使用“text”而不是“html”作为dataType,因为jQuery会尝试将其解析为DOM结构,这不是你想要的。
您的if语句(以及类分配)也不起作用,因为您尝试将其与非excisting变量(而不是具有该值的字符串)进行比较。您应该在字符串周围使用“或”来解决这个问题。
此代码应该正常工作。如果没有,请告诉我。包括浏览器控制台中给出的错误。
$(document).ready(function () {
$('#enviar').click(function (event) {
event.preventDefault(); //avoid page refresh
var consulta = $('#string').val();
$("#normal").text(consulta);
//Start AJAX!
$.ajax({
type: 'POST',
cache: false,
url: 'RELATIVE_PATH_HERE', //la del servr
data: {
html: consulta
},
dataType: 'text',
beforeSend: function () {
console.log('Sending...');
},
success: function (data) {
console.log('Just sent -'+data+'- with success dooh');
$('#ajax').html(data);
//start conditional
if (data === 'pendiente') {
$("#ajax").addClass('pendiente');
} else if (data === 'verificada') {
$("#ajax").addClass('verificada');
} else if (data === 'rechazada') {
$("#ajax").addClass('rechazada');
} else {
$("#ajax").html('<h1>error</h1>');
}
//end condicional
},
complete: function () {
console.log('Listo el pollo');
},
error: function() {
console.log('Problem with XHR-request');
});
});
});
如果您处理多个Ajax调用,请小心使用.addClass,因为它们会互相添加。