将字符串从js传递给php

时间:2015-03-22 20:08:04

标签: javascript php jquery ajax

我是javascript& s的完全初学者PHP。我试图使用ajax将变量从javascript传递给php。我查看了有关此主题的其他一些帖子并尝试复制语法,但某些内容仍无法正常工作。这是代码相关部分的副本(注意:我注释掉了不同的部分):

这有效: 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("\n", 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;

这不起作用: 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("\n", 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;

我得到的错误是:&#34;未捕获的ReferenceError:未定义file_get_contents&#34;。我做错了什么?

0 个答案:

没有答案