使用ajax,php和jQuery更改DIV内容
我有一个div,其中包含数据库的一些文本:
Here is summary of movie
和链接列表:
Name of movie Name of movie ..
这个过程应该是这样的:
- 点击链接
- Ajax使用链接的url通过GET将数据传递到php文件/同一页面
- PHP返回字符串
- div被更改为此字符串
并在列表中添加onclick
事件
View Text This text will be replaced when the onclick event (link is clicked) is triggered.
通过注册锚点的click事件(使用class =“movie”)并使用.load()
方法发送AJAX请求并替换摘要div的内容,您可以使用jQuery轻松实现这一点:
$(function() { $('.movie').click(function() { $('#summary').load(this.href); // it's important to return false from the click // handler in order to cancel the default action // of the link which is to redirect to the url and // execute the AJAX request return false; }); });
试试这个
function getmoviename(id) { var p_url= yoururl from where you get movie name, jQuery.ajax({ type: "GET", url: p_url, data: "id=" + id, success: function(data) { $('#summary').html(data); } }); }
而你的HTML部分是
Name of movie Here is summary of movie
这对我有用,你不需要内联脚本:
使用Javascript:
$(document).ready(function() { $('.showme').bind('click', function() { var id=$(this).attr("id"); var num=$(this).attr("class"); var poststr="request="+num+"&moreinfo="+id; $.ajax({ url:"testme.php", cache:0, data:poststr, success:function(result){ document.getElementById("stuff").innerHTML=result; } }); }); });
HTML:
More stuff 1 More stuff 2 More stuff 3 Here is some stuff that will update when the links above are clicked
请求发送到testme.php:
header("Cache-Control: no-cache"); header("Pragma: nocache"); $request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']); $request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']); if($request_id=="1") { echo "show 1"; } elseif($request_id=="2") { echo "show 2"; } else { echo "show 3"; }
jQuery.load()
$('#summary').load('ajax.php', function() { alert('Loaded.'); });