使用 Ajax 在 jQuery 中返回数据不起作用
我使用 Ajax 和 jQuery 开发了代码。 我收到了来自 my.php 的回复,并且我已经 尝试提取响应的值。 这里是代码(HTML):
My.php
?php
echo '<div id="title">My Title </div>';
echo '<div id="message"> My message </div>';
?>
我尝试提取标题和消息,所以我的代码如下。
<head>
<script type="text/javascript" src="js/jquery-1.2.6.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert("OK");
$.ajax({
type:"POST",
url: "my.php",
cache:false ,
success: function(data){
$("#response").html(data);
var $response = $(data);
var oneval = $response.find('#title').text();
var subval = $response.find('#message').text();
alert(oneval);
}
});
});
</script>
</head>
<body>
<div id="response">
</div>
</body>
</html>
...
问题是当我试图发出警报时,它不起作用。 这个逻辑有什么问题呢? 我应该使用另一个函数来提取标题和消息吗?
I have developed code with Ajax and jQuery. I have got a response from my.php, and I have
tried to extract the values of the response. Here the code (HTML):
My.php
?php
echo '<div id="title">My Title </div>';
echo '<div id="message"> My message </div>';
?>
I try to extract the title and message so my code is below.
<head>
<script type="text/javascript" src="js/jquery-1.2.6.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert("OK");
$.ajax({
type:"POST",
url: "my.php",
cache:false ,
success: function(data){
$("#response").html(data);
var $response = $(data);
var oneval = $response.find('#title').text();
var subval = $response.find('#message').text();
alert(oneval);
}
});
});
</script>
</head>
<body>
<div id="response">
</div>
</body>
</html>
...
The problem is when I tried to alert, it is not working. What is wrong with this logic? Should I use another function to extract the title and message?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好的,转到 http://jsbin.com/udige/ ,您可以看到它正在运行。
关键是使用
.filter
,而不是 .find,因为这两个 div 是响应中的根元素。 我的错。基本上做到以下几点:
OK, go to http://jsbin.com/udige/ and you can see it working.
The key is using
.filter
, not .find as the two divs are root elements in the response. My mistake.Basically do the following:
如果响应按照您编写的方式返回,那么我给您的代码将起作用。
您确实需要学习如何使用调试器(Firebug)并设置断点到您的代码中,以便您可以使用控制台来测试选择器并查看变量的值等。
另外,您确实应该回答我给出的原始问题和答案,而不是提出一个全新的问题,特别是因为您甚至没有交叉引用您的原始问题。
If the response is coming back as you wrote it then the code which I gave you will work.
You really need to learn how to use a debugger (Firebug) and put breakpoints into your code so you can use the console to test selectors and look at the values of variables, etc.
Also you should really have responded to the original question and answer that I gave rather than opening a whole new question especially since you have not even cross referenced your original.
尝试使用这个代替:
Try using this instead: