简体   繁体   English

PHP函数不适用于Ajax

[英]PHP function doesn't work with Ajax

I have some button and on click JS for it: 我有一些按钮,然后单击JS:

<button id="trigger">Send</button>

and JS to invoke simple action 和JS调用简单的动作

$('#trigger').on("click", function(event){ 
                    jQuery.ajax({
                        type: "POST",
                        url: 'functions.php',
                        dataType: 'json',
                        data: {functionname: 'add', arguments: [1, 2]},

                        success: function (obj, textstatus) {
                            alert('test success');
                        },
                        complete: function (obj, textstatus) {
                            alert('test complete');
                        }
                    });
                });

In above ajax I put functions.php with other simple function: 在上面的ajax中,我将functions.php与其他简单函数放在一起:

<?php

$message = "PHP Funtion Alert";
echo "<script type='text/javascript'>alert('$message');</script>";

?>

But, I got only alert invoked from alert('test complete'); 但是,我只从alert('test complete');中调用了Alert。 How invoke alert from PHP file? 如何从PHP文件调用警报?

PS. PS。 this is only example. 这仅是示例。 In PHP file will be some DB functions. 在PHP文件中将包含一些DB函数。

You're expecting JSON, hence the 您期望使用JSON,因此

dataType: 'json',

Yet, you're returning a script tag? 但是,您要返回脚本标签吗?

echo "<script type='text/javascript'>alert('$message');</script>";

And that's an error. 那是一个错误。 What you want is to return valid JSON 您想要的是返回有效的JSON

$message = array("message" => "PHP Funtion Alert");
echo json_encode($message);

Then catch in the ajax function 然后抓住ajax函数

jQuery.ajax({
  type     : "POST",
  url      : 'functions.php',
  dataType : 'json',
  data     : {
    data : 'to be sent'
  }
}).done(function(data) {
  console.log(data.message);
}).fail(function() {
    console.log(arguments);
});

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

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