首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Jquery使用参数加载动态内容

Jquery使用参数加载动态内容
EN

Stack Overflow用户
提问于 2012-05-22 09:14:39
回答 1查看 634关注 0票数 1

我试图根据被点击的a href来加载div内容,并传入一个参数。例如,链接1单击链接1会将值"3“传递给process.php,然后返回"apple is good For you”。

但是,如果没有submit按钮,我似乎无法传递该值。无论如何,我可以将参数传递给另一个php文件进行处理,然后返回值?

代码语言:javascript
运行
复制
$(document).ready(function(){
     $("#testing a").live("click", function(evt){
         var id= $(this).attr('id');
        $.post("process.php", { id: id },
        function(data) {
          alert(data);
                    $('#result').load(data);
        });
     })

});

下面是我的HTML

代码语言:javascript
运行
复制
<div id="testing">
<a href="" id="11"> hello </a>
</div>

<div id="result"></div>

感谢您的帮助,非常感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-05-22 09:20:53

您不应该对id值使用数字。相反,可以用字母作为它们的前缀,或者考虑将它们添加到元素的data-属性中。

此外,$.live()已被弃用,我们鼓励从现在开始使用$.on()进行事件委派。我已经在下面的代码中处理了这个问题,但是id问题仍然存在。

最后,$.load()$.html()是不同的。如果要将data加载到元素中,则不需要调用load方法(尽管名称可能会导致混淆)。

代码语言:javascript
运行
复制
// Short-hand version of $(document).ready();
$(function(){
  // Handle anchor clicks on #testing
  $("#testing").on("click", "a", function(e){
    // Prevent links from sending us away
    e.preventDefault();
    // POST our anchor ID to process.php, and handle the response
    $.post("process.php", { 'id': $(this).attr("id") }, function(data){
      // Set the response as the HTML content of #result
      $("#result").html(data);
    });
  });
});

从您的process.php文件中,您可能具有类似以下内容:

代码语言:javascript
运行
复制
$msg = array( 
    "...chirp chirp...",
    "This is response number 1",
    "And I am the second guy you'll see!",
    "Apples are good for you!" 
);

$num = $_POST["id"] || 0;

echo $msg[ $num ];
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10694615

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档