Pab*_*bar 3 javascript php ajax jquery
你能帮我解决这些问题吗:
我正在进行PHP-Jquery-AJAX-JSON搜索,想法是有一个php表单,在那里键入特定员工的ID,然后通过AJAX显示div中的名称总是在同一个php表单中.
我的问题是,我可以显示我想在div中显示的消息,因为当我按下提交按钮时,它总是重定向到表单中指定的操作页面,而不是只显示消息进入div,所以你能告诉我吗我有什么问题?正如您将看到的,我在代码中指定了e.preventDefault(),如下所示:
$(document).ready(function() {
$("#submit_id").click(function (e) {
e.preventDefault();
var id = $("input#ID_id");
if(validaForm(id)){
$("#submit_id").hide();
var url = $("#form_id").attr('action');
var data = $("#form_id").serialize();
var type = $("#form_id").attr('method');
$("#LoadingImage").show();
$("#ajax_id").html("<div class='cargando'> realizando busqueda</div>");
$.ajax({
url:url,
data:data,
type:type,
cache: false,
contentType: "application/x-www-form-urlencoded",
dataType: 'json',
encode: true
.done(function(data) { // using the done promise callback
if ( ! data.success) {
$("#LoadingImage").fadeOut();
if (data.errors.ID_name) {
$("#ajax_id").html("<div class='cargando'> Debe especificar el ID</div>");
} // if
} // if
else {
$("#ajax_id").html("<div class='cargando'> Tudo Ben</div>");
} // else
}) // done-promise
.fail(function(data) { // using the fail promise callback
console.log(data);
}); // fail-promise
}); // AJAX call
} // validaForm*/
});
});
function validaForm(id){
var id_val = id.val().trim();
if((id_val=="") || id_val.replace(/s+/,'') == ''){
alert("Favor ingrese el ID");
id.addClass("posicionamiento");
$("#div_id").html("<div class='error'>Debe especificar el nombre</div>");
return false;
}else{
id.removeClass("posicionamiento");
$("#div_id").empty();
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<html>
<head>
<title>BUSCADOR</title>
</head>
<body>
<form method="post" id="form_id" action="process.php">
<fieldset>
<legend>Buscador Asincrono</legend>
<p>ID a buscar: <input type="text" name="ID_name" id="ID_id"/>
<div id="estado_id"></div></p>
<p><input type="submit" id="submit_id" value="Buscar"/></p>
<img src="imagenes/cargando.gif" id="LoadingImage" style="display:none" align="center"/> <div id="ajax_id" align="center"></div>
</fieldset>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
您试图阻止点击事件而不是提交本身.
使用.submit(doc)而不是.click在事件处理程序中(并将事件绑定到表单而不是提交按钮):
$(document).ready(function() {
$("#form_id").submit(function (e) {
e.preventDefault();
// ...
Run Code Online (Sandbox Code Playgroud)
如果要在特定点提交表单,则可以使用 $("#form_id").submit();
更新:我找到了一个小提示,找出错误:
你关闭.ajax()得太晚了:-)
$.ajax({
// ...
.done(function(data) { // using the done promise callback
// ...
}) // done-promise
.fail(function(data) { // using the fail promise callback
// ...
}); // fail-promise
}); // AJAX call
Run Code Online (Sandbox Code Playgroud)
将其更改为:
$.ajax({
// ...
}) // AJAX call
.done(function(data) { // using the done promise callback
// ...
}) // done-promise
.fail(function(data) { // using the fail promise callback
// ...
}); // fail-promise
Run Code Online (Sandbox Code Playgroud)
它在小提琴中被纠正了.