jquery ajax返回php脚本而不是json的文本

时间:2014-08-24 20:50:57

标签: php jquery ajax json

我有一个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 registeredCourses = {

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列的意外字符

第二个警告显示:

textStatus:parsererror

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数据?

2 个答案:

答案 0 :(得分:0)

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

$('<option value="' + index + '">' + this['coursecode'] +/option>')在选项关闭标记

之前缺少'<

}结尾)之后还错过了fail。修复这些文件之后,只要填充下拉列表,您的代码就可以为我工作,但由于registeredCourses.getSelected();不存在而导致js错误。这让我想知道上面的代码是否完整?

如果所有这些都无济于事,那么当你直接进入你的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>

答案 1 :(得分:0)

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