简体   繁体   English

使用jQuery将警报文本设置为从PHP文件回显的文本

[英]use jquery to set the text of the alert to text echoed from a php file

I have a PHP file myFile.php that echoes a random string from an array of strings into the screen. 我有一个PHP文件myFile.php ,它将字符串数组中的随机字符串回显到屏幕中。 I want to run that php file and have the output pop up in a javascript alert. 我想运行该php文件,并在javascript警报中弹出输出。 I took a crack at the syntax with alert($.ajax({ url: 'getRejection.php' })); 我用alert($.ajax({ url: 'getRejection.php' }));破解了语法alert($.ajax({ url: 'getRejection.php' }));

But it is not quite right , it alerts [object Object] . 但这并不完全正确,它会警告[object Object]

How do I do this? 我该怎么做呢?

According to the jquery documentation for ajax : http://api.jquery.com/jQuery.ajax/ 根据有关ajax的jquery文档: http : //api.jquery.com/jQuery.ajax/

You want to use the success callback to run when the ajax call succeeds. 您想使用success回调在ajax调用成功时运行。

$.ajax({
    url: 'getRejection.php',
    success: function(data) { alert(data) }
});

Also, a note of advice: use full paths for urls, not relative url paths. 另外,请注意:使用完整路径的URL,而不是相对URL路径。 Like this url: '/getRejection.php' not like this url: 'getRejection.php' 像这个url: '/getRejection.php'不像这个url: '/getRejection.php' url: 'getRejection.php'

You may use JSON by making your php file to echo its output in JSON format as follows: 您可以通过使您的php文件以JSON格式回显其输出来使用JSON,如下所示:

echo "{\n";
  echo "\"txt\":";
  echo $TheRandomText;
  echo "\n";
  echo "}";

The previous step may be easily done as Joe Frambach suggestion like the following: 上一步很容易按照Joe Frambach的建议完成,如下所示:

echo json_encode(array('txt' => $TheRandomText));

And then using Jquery do the following: 然后使用Jquery执行以下操作:

$(document).ready(function(){       
        $.getJSON('getRejection.php',{
          format: "json"
        }).done(function(data){
          alert(data.txt);
        });     
      });

However you have to get assured from the path to getRejection.php . 但是,您必须从getRejection.php的路径中放心。 In this case it is supposed to be at the same directory with your file. 在这种情况下,它应该与文件位于同一目录。

Also you have to be sured that getRejection.php does not echo anything else text in JSON format to void the corruption of JSON query. 另外,您还必须确保getRejection.php不会回显JSON格式的其他任何文本,以使JSON查询的损坏无效。

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

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