在单击链接时使用AJAX替换内容。

时间:2022-01-21 00:30:17

I want to use AJAX to replace the contents of a div. Although the application is fairly complex, I have tried to dumb it down in isolation so that I can get the basic concept working first.

我想使用AJAX替换div的内容。虽然这个应用程序相当复杂,但我尝试将它单独简化,以便让基本概念首先工作。

For now, I just want to replace a div as per the PHP file...

现在,我只想根据PHP文件替换div…

<?php 
$id = $_GET['id'];
if ($id = 1)
    {
        $text = 'This is some text';
    }
elseif ($id = 2) {
    {
        $text = 'This is a lot more text than the first text!';
    }
elseif ($id = 3) {
    {
        $text = 'This is a lot more text than the first text, and a load more than the third as well!!';
    }
echo $text; 
?>

Fairly simple stuff really. So here's my HTML file...

真的相当简单的东西。这是我的HTML文件。

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }


xmlhttp.open("GET","ajax.php",true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv">I want this content replacing</div>
<a href="#" onclick="loadXMLDoc()">ID: 1</a><br>
<a href="#" onclick="loadXMLDoc()">ID: 2</a><br>
<a href="#" onclick="loadXMLDoc()">ID: 3</a>
</body>
</html>

I realise what is there will never work as I've modified some stuff I found online, but basically I'm looking to pass a variable such as the ID in the link to the AJAX script to replace the contents of the div.

我意识到,我在网上找到的一些东西是不会有效果的,但基本上,我想要传递一个变量,比如链接到AJAX脚本的ID,以替换div的内容。

How do I get this working? Is there a better alternative to using <a> tags?

我如何让它工作?有更好的替代方法来使用标签吗?

4 个解决方案

#1


2  

Using jQuery

使用jQuery

Your HTML

HTML

<a href="#" class="ajax" data-id="1">ID: 1</a>

Javascript

Javascript

// Delegate click event
$(document).on('click', 'a.ajax', function(){

    var el = $(this);
    $.ajax({
        url: 'ajax.php',
        data: {id: el.data('id')},
    }).done(function(response){
        $('#myDiv').html(response);
    });

});

#2


1  

I'll answer your question using Vanilla JavaScript rather than using the jQuery AJAX Helper. Although it's very good - but learning the Vanilla way will give you a good idea of what the libraries do to aid you.

我将使用Vanilla JavaScript来回答您的问题,而不是使用jQuery AJAX Helper。虽然它很好,但是学习普通的方法会让你很好地了解图书馆是如何帮助你的。

Firstly, you are making an Ajax call but albeit, an Empty one. "Query" parameters is what $_GET is based on, are formated like:

首先,您正在进行一个Ajax调用,尽管是空调用。“查询”参数是$_GET的基础,形式如下:

?Key=Value&KeyTwo=SomeOtherValue

= Value&KeyTwo = SomeOtherValue ?关键

Which in PHP, Translates too:

在PHP中,也可以翻译为:

Array
(
    [Key] => Value
    [KeyTwo] => SomeOtherValue
)

This'll need to be passed along with the xmlhttp.send() for it to make an successful ajax call, with Data.

这需要与xmlhttp.send()一起传递,以便使用数据进行成功的ajax调用。

But to collect this data in the first place, you must collect it with your HTML:

但是要首先收集这些数据,您必须使用HTML来收集:

<!-- Notice how the <a> tags now have attributes attached, the id="" -->
<a href="#" id="1" onclick="loadXMLDoc( this )">ID: 1</a><br />
<a href="#" id="2" onclick="loadXMLDoc( this )">ID: 2</a>

<script>
function loadXMLDoc( Id ) {

    /**
     *  Id is the <a href="#" id="3" collected 
     *  when onclick="loadXMLDoc()" is pressed
    **/
    var xmlhttp,
        DataId = Id.attributes.id.value;

    if (window.XMLHttpRequest)
       xmlhttp = new XMLHttpRequest();
    else 
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange = function() {
       if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
          document.getElementById("myDiv").innerHTML=xmlhttp.responseText;   
    }

    /**
     *  Notice the ?id="+ dataId +"
     *  It's passing through the ID Collected
    **/
    xmlhttp.open("GET","ajax.php?id="+ dataId +"",true);
    xmlhttp.send();
}
</script>

Although this code above is very inefficient, you would be much better in JavaScript & Programming in general to keep things generic. By modifying your code to:

虽然上面的代码效率非常低,但是在JavaScript和编程方面,您可以做得更好,以保持其通用性。通过修改您的代码到:

<a href="#" id="1" class="idlistener">ID: 1</a><br />
<a href="#" id="2" class="idlistener">ID: 2</a>

<script>
    function getId() {
        alert( this.attributes.id.value );
        //Click on id="2", alerts '2'
    }

    /**
     *  We find all the HTML tags with the
     *  attribute that has 'class="idlistener"
     *  attached, we 'bind' it to a function called
     *      getId()
    **/
    var IdListener = document.getElementsByClassName('idlistener');
    for( var x = 0; x < IdListener.length; x++ ) {
         IdListener[x].addEventListener( 'click', getId, false );
    }
</script>

Demo: Fiddle

演示:小提琴

Lastly, It does look to me you've discovered this AJAX Code from W3Schools.com. I think you'll find every * Web Developer that would agree with me - Don't learn from this Site!

最后,它确实在我看来,您已经从W3Schools.com中发现了这个AJAX代码。我想你会发现每个*网站的开发者都同意我的观点——不要从这个网站上学习!

#3


0  

General format for replacing html content with the response from an ajax call:

用ajax调用的响应替换html内容的通用格式:

$.ajax({
  url: yourUrl,
  method: 'get', // or 'post'
  success: function (response) {
      $('#myDiv').html(response);
  }
  // other ajax options here if you need them
});

#4


0  

You dont need to use ajax for that. Just use the following in the condition. Dont forget to call the jquery js file on the header. Otherwise jquery wont work:

您不需要为此使用ajax。只需要在条件下使用。别忘了在页眉上调用jquery js文件。否则jquery不会工作:

echo '<script>$("#myDiv").html("This is some text")</script>';

#1


2  

Using jQuery

使用jQuery

Your HTML

HTML

<a href="#" class="ajax" data-id="1">ID: 1</a>

Javascript

Javascript

// Delegate click event
$(document).on('click', 'a.ajax', function(){

    var el = $(this);
    $.ajax({
        url: 'ajax.php',
        data: {id: el.data('id')},
    }).done(function(response){
        $('#myDiv').html(response);
    });

});

#2


1  

I'll answer your question using Vanilla JavaScript rather than using the jQuery AJAX Helper. Although it's very good - but learning the Vanilla way will give you a good idea of what the libraries do to aid you.

我将使用Vanilla JavaScript来回答您的问题,而不是使用jQuery AJAX Helper。虽然它很好,但是学习普通的方法会让你很好地了解图书馆是如何帮助你的。

Firstly, you are making an Ajax call but albeit, an Empty one. "Query" parameters is what $_GET is based on, are formated like:

首先,您正在进行一个Ajax调用,尽管是空调用。“查询”参数是$_GET的基础,形式如下:

?Key=Value&KeyTwo=SomeOtherValue

= Value&KeyTwo = SomeOtherValue ?关键

Which in PHP, Translates too:

在PHP中,也可以翻译为:

Array
(
    [Key] => Value
    [KeyTwo] => SomeOtherValue
)

This'll need to be passed along with the xmlhttp.send() for it to make an successful ajax call, with Data.

这需要与xmlhttp.send()一起传递,以便使用数据进行成功的ajax调用。

But to collect this data in the first place, you must collect it with your HTML:

但是要首先收集这些数据,您必须使用HTML来收集:

<!-- Notice how the <a> tags now have attributes attached, the id="" -->
<a href="#" id="1" onclick="loadXMLDoc( this )">ID: 1</a><br />
<a href="#" id="2" onclick="loadXMLDoc( this )">ID: 2</a>

<script>
function loadXMLDoc( Id ) {

    /**
     *  Id is the <a href="#" id="3" collected 
     *  when onclick="loadXMLDoc()" is pressed
    **/
    var xmlhttp,
        DataId = Id.attributes.id.value;

    if (window.XMLHttpRequest)
       xmlhttp = new XMLHttpRequest();
    else 
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange = function() {
       if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
          document.getElementById("myDiv").innerHTML=xmlhttp.responseText;   
    }

    /**
     *  Notice the ?id="+ dataId +"
     *  It's passing through the ID Collected
    **/
    xmlhttp.open("GET","ajax.php?id="+ dataId +"",true);
    xmlhttp.send();
}
</script>

Although this code above is very inefficient, you would be much better in JavaScript & Programming in general to keep things generic. By modifying your code to:

虽然上面的代码效率非常低,但是在JavaScript和编程方面,您可以做得更好,以保持其通用性。通过修改您的代码到:

<a href="#" id="1" class="idlistener">ID: 1</a><br />
<a href="#" id="2" class="idlistener">ID: 2</a>

<script>
    function getId() {
        alert( this.attributes.id.value );
        //Click on id="2", alerts '2'
    }

    /**
     *  We find all the HTML tags with the
     *  attribute that has 'class="idlistener"
     *  attached, we 'bind' it to a function called
     *      getId()
    **/
    var IdListener = document.getElementsByClassName('idlistener');
    for( var x = 0; x < IdListener.length; x++ ) {
         IdListener[x].addEventListener( 'click', getId, false );
    }
</script>

Demo: Fiddle

演示:小提琴

Lastly, It does look to me you've discovered this AJAX Code from W3Schools.com. I think you'll find every * Web Developer that would agree with me - Don't learn from this Site!

最后,它确实在我看来,您已经从W3Schools.com中发现了这个AJAX代码。我想你会发现每个*网站的开发者都同意我的观点——不要从这个网站上学习!

#3


0  

General format for replacing html content with the response from an ajax call:

用ajax调用的响应替换html内容的通用格式:

$.ajax({
  url: yourUrl,
  method: 'get', // or 'post'
  success: function (response) {
      $('#myDiv').html(response);
  }
  // other ajax options here if you need them
});

#4


0  

You dont need to use ajax for that. Just use the following in the condition. Dont forget to call the jquery js file on the header. Otherwise jquery wont work:

您不需要为此使用ajax。只需要在条件下使用。别忘了在页眉上调用jquery js文件。否则jquery不会工作:

echo '<script>$("#myDiv").html("This is some text")</script>';