简体   繁体   English

使用 XMLHttpRequest 的 PHP AJAX CALL

[英]PHP AJAX CALL using XMLHttpRequest

I'm working on a PHP project and need to do an ajax call however it's set up in such a way that "ve never seen before. I have one file: index.php that looks like this:我正在处理一个 PHP 项目,需要执行一个 ajax 调用,但是它的设置方式“以前从未见过。我有一个文件:index.php,它看起来像这样:

echo '<input id=ajax_redraw name=ajax_redraw type=button value="Redraw" onclick="ajaxTest()" />';
echo '<div id=destination_div name=destination_div class=ajax_test >';
echo '</div>';

echo end_page();

function redraw_destination_div()
{
    global $db;

    $select = $db->select()
                ->from( EPRESCRIBING_ERROR_MESSAGES, 'error_message' );
    $errors = $db->fetchCol( $select );

    $random_key = rand( 0, (count($errors)-1) );
    $errror_message_for_destination_div = $errors[$random_key];

}

I need to show the variable $errror_message_for_destination_div on the div with the id of destination_div.我需要在带有destination_div id 的div 上显示变量$errror_message_for_destination_div。

My javascript code looks like this:我的 javascript 代码如下所示:

function ajaxTest() {

  // Getting the specific div to target
  var targetArea = document.getElementById("destination_div");
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("POST", "ajax_test.php", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.onreadystatechange = function() {
    if (this.readyState === 4 || this.status === 200){ 
        targetArea.innerHTML = 'SEE ME';
        console.log(this.responseText); // echo from php
    }       
  };
  xmlhttp.send(); 


}

I can display the 'See Me' text no problem.我可以毫无问题地显示“See Me”文本。 I just need to know how to call and display the response from the PHP function redraw_destination_div.我只需要知道如何调用和显示来自 PHP 函数 redraw_destination_div 的响应。 Thank you for any help.感谢您的任何帮助。

You need to rewrite the PHP.你需要重写PHP。

HTTP requests are made to URLs, not functions. HTTP 请求是针对 URL 而不是函数。

You need a URL which you can make a request to get the data you need (and only the data you need).您需要一个 URL,您可以通过该 URL 请求获取所需数据(并且获取所需数据)。

Currently you have a PHP program which:目前你有一个 PHP 程序,它:

  • Outputs a <div> you don't want in the Ajax response.在 Ajax 响应中输出您不需要<div>
  • Creates a function which stores the data you want in a variable.创建一个函数,将所需的数据存储在变量中。
  • Doesn't call that function.不调用该函数。
  • Doesn't output the contents of the variable in the response.不输出响应中变量的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM