Didn"t forge 2013-11-01 14:22 采纳率: 25%
浏览 331

将json对象保存到文件

I need to save a json object to a file. Therefore I'm using another PHP script which writes the data to a file. Data and filename are sent by an ajax POST request.

var results = $('results');
var filename = $('#filename').val();

$.ajax({
    url: 'jsonWriter.php',
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify([{data: data, filename: filename }]),
    success: function(data) {
        results.html(data);
    },
    error: function(jqXhr, textStatus, error) {
        results.html("<p class=\"error\">ERROR: " + textStatus + ", " + error + "</p>");
    }
});

When I monitor the request in Fiddler, it looks fine and the posted data is correct. However, somehow the error function is invoked. It outputs

ERROR: parsererror, SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

I copied the posted JSON data from Fiddler into different online parsers, which ensured it is valid.

Why is the error function invoked anyway?

  • 写回答

1条回答

  • weixin_33716941 2013-11-01 14:27
    关注

    It looks to me like you are expecting the server to return text content, since you are applying it with .html:

    success: function(data) {
        results.html(data);
    },
    

    However, you are telling jQuery to expect JSON data:

    dataType: "json",
    

    jQuery is therefore attempting to parse your content returned from the server as JSON and failing. You need to change dataType to either text or html.

    评论

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏