【问题标题】:jquery ajax returning text of php script instead of jsonjquery ajax返回php脚本的文本而不是json
【发布时间】:2014-10-18 00:44:49
【问题描述】:

我有一个直接执行时可以正常工作的 php 脚本: PHP:

<?php
    header('Content-Type: application/json');
    $fileName = "../appfiles/Courses.json";
    if (file_exists($fileName)) 
      {
    $json = json_decode(file_get_contents($fileName), true);
        echo json_encode($json);
      } 
    else 
      {
        echo "The file $fileName does not exist";
      }
    ; 
?>

跑步

http://localhost/RickVideos/php/getRegCourses.php

,我明白了:

[{"coursecode":"ACCTD_001","cflag":"Y","pflag":"Y","dateregistered":"08\/11\/14","timeregistered":"12:55 pm."},{"coursecode":"LWPRG1_004","cflag":"Y","pflag":"Y","dateregistered":"08\/18\/14","timeregistered":"3:30 pm."},{"coursecode":"LWPRG2_005","cflag":"Y","pflag":"Y","dateregistered":"08\/18\/14","timeregistered":"3:32 pm."}]

尝试从 jquery ajax 运行 php,返回的似乎是脚本文本而不是 json 数据。

JavaScript:

// registered courses

var 注册课程 = {

init: function () 
    {
        $.ajax(
            {   
                type: 'POST',
                dataType: "JSON",
                url: "php/getRegCourses.php",
            }
        )

        .done(function(data) 
            { 
                $.each(data, function(index, element) 
                    {
                        $('#registeredCourses').append(
                        $('<option value="' +   index + '">' + this['coursecode'] + '</option>')
                        );
                    }
                );      
                $('#registeredCourses').val('0');
                $("#registeredCourses").trigger('chosen:updated');
                registeredCourses.getSelected();    
            }
        )
        .fail (function(jqXHR, textStatus, errorThrown )
            {
                alert('request failed :'+errorThrown);
                alert ('textStatus :'+textStatus);
                console.log(jqXHR);
            }
        );
    },

getSelected: function () 
    {
        $.ajax(
            {
                type: 'GET',
                url: "getSelCourseInfo.php",
                data: 
                    {
                        course: $("#registeredCourses option:selected").text() 
                    }
            }
        )

        .done(function( data ) 
            {
                $("#courseCode").val($("#registeredCourses option:selected").text());
                $("#courseTitle").val(data.Title);
                $("#projectManager").val(data.ProjectManager);                         
                $("#initRegDate").val (data.LastModDate + ' at ' +  data.LastModTime);

                var tasks = [ ];
                $.each(data.ProjectTasks, function(i, item) 
                    {       
                        $("#projectTasks").append(
                            '<tr>' +
                            '<td>' + this + '</td>' +
                            '</tr>'
                        );
                        tasks[i] = this;
                    }
                );

                var projectMems = [ ];
                $.each(data.ProjectMembers, function(i, item)
                    {       
                        $("#projectMembers").append(
                            '<tr>' +
                            '<td>' + this.PersonName + '</td>' +
                            '<td>' + this.EmailAddress + '</td>' +
                            '</tr>'
                        );
                        projectMems[i] = this.PersonName;
                    }
                );

                $("#selectedCourseData").find("tr:gt(0)").remove();
                $.each(data.Chapters, function(i, item) 
                    {
                        $("#selectedCourseData").append(
                            '<tr>' +
                            '<td>' + this.label + '</td>' +
                            '<td>' + this.title + '</td>' +
                            '<td>' + registeredCourses.makeList('Sciptwriter1', i, projectMems, this.ScriptWriter) + '</td>' +
                            '<td>' + registeredCourses.makeList('Recorder1', i, projectMems, this.Recorder) + '</td>' +
                            '<td>' + registeredCourses.makeList('Status1', i, tasks, this.Status) + '</td>' +
                            '<td>' + registeredCourses.makeList('Assignedto1', i, projectMems, this.Assignedto) + '</td>' +
                            '</tr>'
                        );
                    }
                );

            }
        ); 


    },

    makeList: function (cname, num, array, selected) 
        {
            var string = '<select class="' + cname +'">';
            if (selected== " " && array[0] != " ") 
                {
                array.splice(0, 0, " ");
            };
            for (var i=0; i < array.length; i++) 
                {
                    if (array[i]==selected) 
                        {
                            string = string + '<option value="' + array[i] + '" selected>' + array[i]  + '</option>';
                    }
                    else 
                        {
                            string = string + '<option value="' + array[i] + '">' + array[i]  + '</option>';
                    };
            };

            string = string + '</select>';
            return string;
        }

};

第一个警报显示:

请求失败:SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符

第二个警报显示:

文本状态:解析器错误

jqXHR 对象的响应文本显示:

"<?php header('Content-Type: application/json'); $fileName = "../appfiles/Courses.json"; if (file_exists($fileName)) { $json = json_decode(file_get_contents($fileName), true); echo json_encode($json); } else { echo "The file $fileName does not exist"; } ; ?> "

为什么显示的是脚本文本而不是 json 数据?

【问题讨论】:

  • 这特别奇怪,因为您提到直接调用文件可以正常工作。也许在这里您可以找到一些东西:stackoverflow.com/a/5121589/2433843 如果没有,请在浏览器中检查您的网络窗口,您可以在其中查看标题是否和响应等都是正确的。
  • 查看这个问题的第一个答案:stackoverflow.com/questions/16012815/…。另外,我注意到您发布的代码中有一个未封闭的字符串:“+ /option>')”。应该是:" + '/option')"
  • 我重新发布了代码,包括缺少的功能。
  • 在从 ajax 调用中消除 dataType 后,我重新运行了代码,现在将其作为第一个警报结果:request failed :Error: Invalid XML:

标签: php jquery ajax json


【解决方案1】:

不确定这是否有帮助,但以下代码对我有用。使用您的 json、php 和 html 文件设置一个目录,基本上只是填充选择菜单。这对我来说很好,在查看您的代码时出现了一些 js 错误:

$('&lt;option value="' + index + '"&gt;' + this['coursecode'] +/option&gt;') 在选项关闭标记之前缺少'&lt;

fail 末尾的) 之后还缺少}。修复这些文件后,您的代码在填充下拉列表时对我有用,但您会收到 js 错误,因为 registeredCourses.getSelected(); 不存在。这让我想知道上面的代码是否完整?

如果这一切都无济于事,那么您是否查看了直接访问 php 文件时输出的原始 html,例如查看源代码?

`bonk.php`
<?php
    header('Content-Type: application/json');
    $fileName = "courses.json";
    if (file_exists($fileName))
      {
    $json = json_decode(file_get_contents($fileName), true);
        echo json_encode($json);
      }
    else
      {
        echo "The file $fileName does not exist";
      }
    ;
?>

`courses.json`
[
    {
        "coursecode": "ACCTD_001",
        "cflag": "Y",
        "pflag": "Y",
        "dateregistered": "08/11/14",
        "timeregistered": "12:55 pm."
    },
    {
        "coursecode": "LWPRG1_004",
        "cflag": "Y",
        "pflag": "Y",
        "dateregistered": "08/18/14",
        "timeregistered": "3:30 pm."
    },
    {
        "coursecode": "LWPRG2_005",
        "cflag": "Y",
        "pflag": "Y",
        "dateregistered": "08/18/14",
        "timeregistered": "3:32 pm."
    }
]

`html file`
<html>
<head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>

    var registeredCourses = {
      init: function (){
        $.ajax ({
          type: 'GET',
          dataType: "JSON",
          url: "bonk.php",
        })

        .done(function(data){
          $.each(data, function(index, element){
            $('#registeredCourses')
              .append($("<option></option>")
              .attr("value",index)
              .text(this['coursecode']));
          });
        })

        .fail (function(jqXHR, textStatus, errorThrown){
          console.log(errorThrown, textStatus, jqXHR);
        })
      }
    };

    registeredCourses.init();
  </script>
  </head>
  <body>
    <select name="test" id="registeredCourses"></select>
  </body>
</html>

【讨论】:

  • 我重新发布了包含缺失函数的js代码。提到的 js 错误是在我试图编辑提出问题的代码时引入的。
  • 直接访问 php 文件时查看 HTML 源代码看起来就像显示一样 - 没有任何额外内容。
  • 你用的是什么版本的php?
  • 当前 PHP 版本:5.4.24
  • 我在运行您的代码时遇到了一个错误,即 $ 未定义。我将第一个脚本更改为指向 js/jquery-1.11.1.min.js 并添加一个 $(document).ready(function () { 作为第二个脚本的第一行和一个 });在末尾。在 firebug 中,控制台显示: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data ...SON.parse(b+"");var c,d=null,e=m.trim(b+ "");return e&&!m.trim(e.replace(xc,funct...
【解决方案2】:

我将 php 文件和 Courses.json 文件都转换为 utf-8,它现在可以运行了。

【讨论】:

    猜你喜欢
    • 2012-10-02
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    相关资源
    最近更新 更多