weixin_33739523 2015-03-22 20:08 采纳率: 0%
浏览 35

将字符串从js传递到php

I'm a complete beginner at javascript & php. I'm trying to pass a variable from javascript to php using ajax. I looked at some of the other posts on this topic and tried to copy the syntax, but something's still not working. Here's a copy of the relevant part of the code (note: I commented out the parts that differ):

This works: PHP:

<?php
// Reads in tab-delimited file and outputs json file
$csv = file_get_contents("status.txt")
//$csv = $_POST['csv'];
function csvToJson($csv) {
    $rows = explode("
", trim($csv));
    $data = array_slice($rows, 1);
    $keys = array_fill(0, count($data), $rows[0]);
    $json = array_map(function ($row, $key) {
        return array_combine(str_getcsv($key), str_getcsv($row));
    }, $data, $keys);

    return json_encode($json);
}

$json = csvToJson($csv);
return $json;
?>

JS:

function initialize() {
// Create data variables, calling .ajax to convert tab-delimited to csv file
//    var csv = file_get_contents("status.txt");
    var status = $.ajax({
//      type: "POST",
        url: "statusgetJson.php",
//      data: {"csv": csv},
        dataType:"json",
        async: false
    }).responseText;

This doesn't work: PHP:

<?php
// Reads in tab-delimited file and outputs json file
//$csv = file_get_contents("status.txt")
$csv = $_POST['csv'];
function csvToJson($csv) {
    $rows = explode("
", trim($csv));
    $data = array_slice($rows, 1);
    $keys = array_fill(0, count($data), $rows[0]);
    $json = array_map(function ($row, $key) {
        return array_combine(str_getcsv($key), str_getcsv($row));
    }, $data, $keys);

    return json_encode($json);
}

$json = csvToJson($csv);
return $json;
?>

JS:

function initialize() {
// Create data variables, calling .ajax to convert tab-delimited to csv file
    var csv = file_get_contents("status.txt");
    var status = $.ajax({
        type: "POST",
        url: "statusgetJson.php",
        data: {"csv": csv},
        dataType:"json",
        async: false
    }).responseText;

The error I get is: "Uncaught ReferenceError: file_get_contents is not defined". What am I doing wrong?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
    • ¥15 微信会员卡接入微信支付商户号收款
    • ¥15 如何获取烟草零售终端数据
    • ¥15 数学建模招标中位数问题
    • ¥15 phython路径名过长报错 不知道什么问题
    • ¥15 深度学习中模型转换该怎么实现
    • ¥15 Stata外部命令安装问题求帮助!
    • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
    • ¥15 如何用python向钉钉机器人发送可以放大的图片?
    • ¥15 matlab(相关搜索:紧聚焦)