包括使用jQuery和AJAX一个DIV内PHP文件

问题描述:

我的问题是,我需要包括一个DIV里面的PHP文件按钮时无需重新加载页面按下。包括使用jQuery和AJAX一个DIV内PHP文件

有一个在“的jsfiddle”文件甚至更多的解释。

下面是一个包含文件的jsfiddle。

http://jsfiddle.net/jjygp/5/

感谢您的时间。我很乐意根据要求提供任何信息。

尝试以下操作:

<button name="Change" id="Change">Change Div</button> 

你是一个ID指定点击功能,但没有ID设置按钮。

here for your updated jsfiddle

您已经打上Change名称更改按钮,但试图与change的ID来选择它。另外,你还没有告诉jsfiddle包含jQuery。

+0

对不起,那是对的jsfiddle错误的,不符合我的实际代码。对于那个很抱歉。 – tushar747 2012-01-06 13:54:46

你可以用load()函数尝试jQuery的

http://api.jquery.com/load/

你不能在与AJAX PHP文件,而是在AJAX服务器端脚本,这是PHP的响应(其中有同样的效果)。

载入中...

的JS文件(代码):

function ajaxalizeDiv() 
{ 
    $.ajax({ 
     type: "get", 
     url: "/path/to/the/php/you/want/to/include", 
     data: { 
      // Anything in json format you may want to include 
      id: myvarwithid, // descriptive example 
      action: "read" // descriptive example 
     }, 
     dataType: "json", 
     success: onAjax 
    }); 
} 

function onAjax(res) 
{ 
    if(!res || !res.text) 
     return; 

    $("#mydiv").html(res.text); 
} 

这里而来的PHP文件:

<?php 
    $id = (int) @$_GET['id']; // same as in data part of ajax query request 
    $action = @$_GET['action']; // same as in data part of ajax query request 

    $text = '<a href="/index.php?id=' . $id . '&action=' . $action . '">click me</a>'; 

    // Note this is short example you may want to echo instead of die 
    // You may use not JSON, but raw text. However, JSON is more human-friendy (readable) 
    // and easy to maintain. 
    // Note also the array keys are used in the onAjax function form res (response). 
    die(json_encode(array('text' => $text /* and anything else you want */))); 
?> 

PHP是一种服务器端脚本语言,它将在JavaScript脚本执行之前执行。

因此,您不能使用​​执行PHP代码,但是,您可以尝试.ajax()向可以实现PHP代码的服务器创建AJAX请求。

请参阅http://api.jquery.com/jQuery.ajax/如果你有使用.ajax()麻烦。

注意:在.ajax()方法中,存在一个名为beforeSend的设置,该设置“可用于在发送之前修改jqXHR(在jQuery 1.4.x,XMLHTTPRequest中)”对象。希望这种方法以任何方式帮助你。

然后,你的JavaScript代码将是这样的:

$(document).ready(function(){ 
    $("#Change").click(function(){ 
    //doing AJAX request 
    $.ajax({ 
     url:"include/start10.php", 
     beforeSend:function(){ 
     $('#myDiv').fadeOut('slow'); 
     }, 
     success:function(data){ 
     // do something with the return data if you have 
     // the return data could be a plain-text, or HTML, or JSON, or JSONP, depends on your needs, if you do ha 

     $('#myDiv').fadeIn('slow'); 
     } 
    });  
    }); 
}); 
+0

这将工作与PHP页面上完整?我希望这个功能像“PHP include”一样工作。 – tushar747 2012-01-06 13:53:41

+0

@ tushar747很抱歉如此迟到的回应。与PHP相比,Javascript是一种完全不同的语言,但它们可以在HTML文档中一起工作,例如:'

' – 2017-03-24 10:57:57