jQuery提交表单,然后在现有的div中显示结果

我有一个简单的文本输入表单,提交时需要获取一个php文件(将输入传递给文件),然后将结果(仅一行文本)放入a div并将其淡入div视图。


这是我现在所拥有的:


<form id=create method=POST action=create.php>

<input type=text name=url>

<input type="submit" value="Create" /> 


<div id=created></div>

我需要的是create.php?url=INPUT要动态加载到被div调用中的结果created。


我有jquery表单脚本,但是我无法使其正常工作。但是我确实加载了库(文件)。


千巷猫影
浏览 805回答 3
3回答

慕仙森

此代码应该做到这一点。您不需要像以下这样简单的表单插件:$('#create').submit(function() { // catch the form's submit event&nbsp; &nbsp; $.ajax({ // create an AJAX call...&nbsp; &nbsp; &nbsp; &nbsp; data: $(this).serialize(), // get the form data&nbsp; &nbsp; &nbsp; &nbsp; type: $(this).attr('method'), // GET or POST&nbsp; &nbsp; &nbsp; &nbsp; url: $(this).attr('action'), // the file to call&nbsp; &nbsp; &nbsp; &nbsp; success: function(response) { // on success..&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#created').html(response); // update the DIV&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; return false; // cancel original event to prevent form submitting});

慕妹3146593

这也适用于文件上传$(document).on("submit", "form", function(event){&nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; var url=$(this).attr("action");&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; url: url,&nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; dataType: "JSON",&nbsp; &nbsp; &nbsp; &nbsp; data: new FormData(this),&nbsp; &nbsp; &nbsp; &nbsp; processData: false,&nbsp; &nbsp; &nbsp; &nbsp; contentType: false,&nbsp; &nbsp; &nbsp; &nbsp; success: function (data, status)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#created').html(data); //content loads here&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; error: function (xhr, desc, err)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("error");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;});

UYOU

如果您不希望刷新页面,则必须使用AJAX发布表单。$('#create').submit(function () {&nbsp; &nbsp; $.post('create.php', $('#create').serialize(), function (data, textStatus) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$('#created').append(data);&nbsp; &nbsp; });&nbsp; &nbsp; return false;});
打开App,查看更多内容
随时随地看视频慕课网APP