jQuery AJAX调用PHP脚本并返回字符串


jQuery AJAX Call to PHP Script with String Return

我的目标是在PHP中复制ASP.NET中的Hot Towel SPA框架。

我的项目中有两个文件:show.js和displaystring.php。我基本上想做的是返回displaystring()函数中的任何内容。但由于一系列尝试都没有成功,我在shows.js文件中插入了调试器语句(如下面源代码中所标记的),以找出问题所在。当我在Google Chrome中运行该项目并打开开发工具(Ctrl+Shift+I)时,我看到程序流在调试器语句处停止(正如预期的那样),当我将鼠标悬停在success属性中的数据变量上时,我发现displaystring.php文件会向我返回整个html源代码,而不仅仅是返回".$_POST('string');语句。

我在互联网上尝试了很多解决方案,但都无济于事。有人能告诉我我到底哪里错了吗?非常感谢。

show.js

define(function (require) {
    var val = "";
    //var moviesRepository = require("repositories/moviesRepository");
    $.ajax({
      url: "controllers/displaystring.php",
      type: "post",
      data: {input:"show"},
      datatype: 'json',
      success: function(data){
            val = data;      
        debugger; // Debugger inserted here.
      }});
    return {
        result: ko.observable(),
        activate: function() {
            this.result(val);
        }
    };
});

displaystring.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>String Display</title>
</head>
<body>
<?php
    function displayString() {
        return "The string passed is: ".$_POST('string');   
    }
    displayString();
?>
</body>
</html>

尝试这种方式

displaystring.php :
<?php
    function displayString() {
        return "The string passed is: ".$_POST['input'];   
    }
    echo displayString();
?>

首先必须指定标头:

header('Content-type: text/json');
header('Content-type: application/json');

第二,你必须为这种标题形成你的内容:

<?php
    function displayString() {
        return json_encode($_POST);   
    }
    echo displayString();
?>

此外,你必须阅读官方文件:

  1. php中的标头
  2. JSON格式

php文件必须是这样的:

<?php
     header('Content-type: text/json');
     function displayString() {
                return json_encode($_POST);   
            }
            echo displayString();

好吧,在我的头撞了一整天的石墙之后,我自己找到了解决方案。

我只是稍微修改了一下代码,以便找到问题的答案。

show.js

define(function (require) { 
    return {
        result: ko.observable(),
        activate: function() {
            //var moviesRepository = require("repositories/moviesRepository");
            var self = this;
            $.ajax({
                url: "controllers/displaystring.php",
                type: "get",
                data: {input:"show"},
                dataType: "html",
                success: function(data){
                    self.result(data);
                    debugger;
                }});
        }
    };
});

displaystring.php

<?php
    function display() {
        echo 'Hi I am some random '.rand().' output from the server.';
    }
    display();
    //echo "Hello World!";
?>

就这样!您不必为PHP文件键入整个HTML代码。只要包含PHP脚本,您就会得到输出。

非常感谢大家的帮助

只有像@tyagi这样的PHP脚本&将$_POST("字符串")更改为$_POST["字符串"]。

确保您没有在配置文件或构造函数或类似文件中打印html。我也遇到了同样的问题。解决方案是创建单独的文件来处理ajax请求。