我有一个问题,我使用jQuery / Ajax来运行表单,将数据发送到外部文件,然后更新我的页面的一部分。但是我遇到了一个问题:
外部网站有效。当我手动运行站点时,它会使用id="content"
打印出此div。
但是当我试图通过jQuery从另一个文档接收这些数据时,它不会返回此字段。
它运行外部文件上的所有其他代码就好了,因为它在外部文件中执行数据库调用就好了。但是没有返回数据,就像代码执行时一样," testlog" div(这里的文字)只是消失了,但是没有被替换。
那么你能帮我解释为什么我无法从外部文件中检索数据吗?
首先,这是我要导入的文件的相关部分:
<script>
$(document).ready(function() {
$( "#moveN" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
var $form = $( this );
term = $form.find( "input[name='direction']" ).val();
var posting = $.post( "/modules/world/movement/move.php", { direction: term } );
posting.done(function( data ) {
var content = $("#content", data).html();
$( "#testlog" ).html( content );
});
});
});
</script>
<div id="testlog">Text here<div>
这里是外部文件的相关部分:
<div id="content">
Part i want imported. This should be filled in with data from this external file, but now we are just trying to get the retrieved by the other file.
</div>
我希望你们中的一些人可以帮助新手:)
答案 0 :(得分:3)
如果 content 是根,您将无法找到该元素,您需要对其进行过滤。
更改
var content = $("#content", data).html();
到
var content = $(data).filter("#content").html();
答案 1 :(得分:-1)
你可以使用jQuery.get()从html表单页面获取html
$.get( "ajax/form-page.html", function( data ) {
//here you have acess to the html form the form page
$( ".result" ).html( data );
alert( "Load was performed." );
});
jQuery.get()是一个简写的Ajax函数,相当于:
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
另一个选择是使用jquery的加载函数
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div2").load("form.html");
});
});
</script>
</head>
<body>
<div id="div1"><h2>jQuery AJAX Load</h2></div>
<div id="div2"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
答案 2 :(得分:-1)
尝试将成功函数作为参数发送到jQuery.post
:
<script>
$(document).ready(function() {
$( "#moveN" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
var $form = $( this );
term = $form.find( "input[name='direction']" ).val();
var posting = $.post( "/modules/world/movement/move.php", { direction: term },
function( data ) {
var content = $("#content", data).html();
$( "#testlog" ).html( content );
});
});
});
</script>
<div id="testlog">Text here<div>
参见参考文档:https://api.jquery.com/jQuery.post/
另请参阅参考文献中done
函数没有收到任何数据,只有成功函数作为参数传递。