【问题标题】:Retrieving json data with jquery in html local file在 html 本地文件中使用 jquery 检索 json 数据
【发布时间】:2013-11-27 06:06:54
【问题描述】:

我需要帮助!我想从 Codeigniter 服务器检索 json 数据。 这是我的 html 本地文件 (d://myproject/index.html)

$.ajax({
    type: "POST",
    url : serverUrl+'mobcontroller/users/',
    crossDomain: true,
    async: false,
    data : $("#formlogin").serialize(),
    dataType : MobileJsonType[1],
    beforeSend : function(){//do stuff here},
    success : function(responseData) {
        alert(JSON.stringify(responseData));
    },
    error : function(jqXHR, textStatus, errorThrown) {
        // do stuff here    
    },
    complete: function(xhr, settings){
        alert(JSON.stringify(xhr)+'\n'+settings);
    }
 });

codeigniter 控制器看起来像这样

public function index()
{
    $type_message = 'success';
    $message = 'Mobile plateform';
    $this->output->set_header("Access-Control-Allow-Origin: *");
    $this->output->set_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
    $this->output->set_status_header(200);
    $this->output->set_content_type('application/json');
    $this->output->_display();
    echo json_encode( array('type_message' => $type_message, 'message' => $message) );
}

我获得了带有js错误的json数据响应

Uncaught SyntaxError: Unexpected token : 

请帮帮我!

【问题讨论】:

  • 试试这个,成功:function(responseData) { alert(responseData.type_message);}。假定 MobileJsonType[1] 值为 json

标签: html json codeigniter


【解决方案1】:

将你的成功函数改为

success: function(data) {
    console.log(data)
} 

让我们知道输出是什么。

我不熟悉 codeigniter,但是 $this->output->_display(); 有可能吗?回显 JS 试图解析的东西?如果你放置

ob_clean();

在你的上方

 echo json_encode(...

它将清除要发送回 JS 的缓冲区,这样只有您编码的 JSON 会返回 JS 可以解析的内容。

【讨论】:

    【解决方案2】:

    你的 ajax 请求应该是这样的。

    $.ajax({
        type: "POST",
        url : serverUrl+'mobcontroller/users/',
        crossDomain: true,
        async: false,
        data : $("#formlogin").serialize(),
        beforeSend : function(){//do stuff here},
        success : function(responseData) {
            alert(JSON.stringify(responseData));
        },
        error : function(jqXHR, textStatus, errorThrown) {
            // do stuff here    
        },
        complete: function(xhr, settings){
            alert(JSON.stringify(xhr)+'\n'+settings);
        }
     });
    

    我已删除属性数据dataType : MobileJsonType[1]
    你也不需要使用JSON.stringify。 由于php的json_encode,返回的结果已经是json了

    而您面临的错误是由于beforeSend 造成的,因为beforeSend 首先访问服务器以检查请求是否被允许。如果它发送 true,则实际请求将继续,否则您需要自己处理。我假设您需要发送一些带有序列化数据的令牌。希望能帮助到你。如果您删除属性beforeSend,我认为该请求将正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 2013-09-09
      • 2022-07-20
      相关资源
      最近更新 更多