dongtuo3795 2017-01-15 21:37
浏览 50
已采纳

通过AJAX将JavaScript数组转换为PHP

I have written a simple JS script, that saves mouse positions in an array, which I then send to a php function via AJAX. It works, and saves the recieved data, but the problem is how it is saved, i.e. i would expect to have a normal output of the x and y position as is: [x1,y1],[x2,y2],[x3,y3],...

But what i get is something like this: a:63:{i:0;a:2:{i:0;i:527;i:1;i:1010;}i:1;a:2:{i:0;i:490;i:1;i:1205;}i:2;a:2:{i:0;i:588;i:1;i:1311;}i:3;a:2:{i:0;i:615;i:1;i:1368;}i:4;a:2:{i:0;i:553;i:1;i:1474;}i:5;...

I thought if i encode it in JSON format that it would save as i thought, but i dont understand why the output is as it is. Any ideas?

The JS code is as follows:

window.onbeforeunload = function() {
  var jsonString = JSON.stringify(tabela);
    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: {
            text1: jsonString
        }
    });
}

And the PHP side is this:

    $text1 = json_decode(stripslashes($_POST['text1']));
    $string_data = serialize($text1);
    file_put_contents("your-file.txt", $string_data);
    
  • 写回答

1条回答 默认 最新

  • douyalin0847 2017-01-15 21:41
    关注

    The content looks like this in the file, because you passed the array through serialize function. In order to "decode" file content, use unserialize. If you want to have more human-readable file content, just store the JSON string in the file ($_POST['text1'] directly) or instead of serialize use json_encode again before calling file_put_contents.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 网络打印机Ip地址自动获取出现问题
    • ¥15 求局部放电案例库,用于预测局部放电类型
    • ¥100 QT Open62541
    • ¥15 stata合并季度数据和日度数据
    • ¥15 谁能提供rabbitmq,erlang,socat压缩包,记住版本要对应
    • ¥15 Vue3 中使用 `vue-router` 只能跳转到主页面?
    • ¥15 用QT,进行QGIS二次开发,如何在添加栅格图层时,将黑白的矢量图渲染成彩色
    • ¥50 监控摄像头 乐橙和家亲版 保存sd卡的文件怎么打开?视频怎么播放?
    • ¥15 Python的Py-QT扩展库开发GUI
    • ¥60 提问一下周期性信信号的问题