【问题标题】:Ajax to php wont workAjax 到 php 不起作用
【发布时间】:2012-07-23 10:43:56
【问题描述】:

我正在尝试将事件侦听器附加到单击时将进行 ajax 调用的按钮。

我在一个名为 test.php 的文件中留出了一些 php。 我使用了实时 jquery 函数来攻击按钮的点击事件。 ajax 函数会将页面上输入元素的值传递给 test.php。 然后 test.php 文件将使用该值来确定要使用的文件的 url。 test.php 文件根据匹配的电子邮件对 csv 文件进行重复数据删除。 csv 文件通过上传输入元素上传。

这是我的代码,目前不工作。 Fiddler 显示正在向服务器发送请求,但没有响应。

HTML

<input type="button" id="csv_dedupe" value="dedupe-file">

jQuery

$_CFG_PROCESSORFILE = "http://localhost/Gene/IMEXporter/include/IMEXporter_processor.php";

$("#csv_dedupe").live("click", function(e) {
    file_name = 'C:\\server\\xampp\\Gene\\IMEXporter\\include\\files\\' + $("#IMEXp_import_var-uploadFile-file").val();
    $.post($_CFG_PROCESSORFILE, {"task": "csv_dupe", "file_name": file_name}, function(data) {
        alert("success");
    }, "json")
});

PHP

if ($task == "csv_dupe") {
$input_filename = $_REQUEST["file_name"];
$output_filename = $_REQUEST["file_name"];

$input_file = fopen($input_filename, 'r');
$output_file = fopen($output_filename, 'w');
$email_addresses = array();
// Read the header
$headers = fgetcsv($input_file, 0);
fputcsv($output_file, $headers);
// Flip it so it becomes name => ID
$headers = array_flip($headers);

// Read every row
while (($row = fgetcsv($input_file, 0)) !== FALSE)
{
    $email = $row[$headers['email']];
    // Do we already have this email address?
    if (isset($email_addresses[$email]))
        continue;

    // Mark this email as being found
    $email_addresses[$email] = true;
    // Write it to the output
    fputcsv($output_file, $row);
}

}

我似乎无法弄清楚为什么它不起作用以及我做错了什么。任何想法都将不胜感激。

编辑 *已修复但显示新错误*

请求返回时我收到了一些错误。

警告:fputcsv() 期望参数 2 为数组,布尔值在 C:\server\xampp\htdocs\Gene\IMEXporter\include\IMEXporter_processor.php 第 45 行给出

警告:array_flip() 期望参数 1 是数组,布尔值在 C:\server\xampp\htdocs\Gene\IMEXporter\include\IMEXporter_processor.php 第 47 行给出 “成功”

【问题讨论】:

  • 您没有回应 PHP 的任何答案,请尝试在末尾添加:echo json_encode("success");
  • 我添加了 "echo json_encode("success");"到 if 子句的末尾,就在 php 中的最后一个括号之前,但不幸的是它不起作用。
  • 您是否尝试过从 json 更改为 jsonp,因为它看起来像是跨域帖子..
  • 我能够从控制台中找出一些错误。这是它报告的内容 警告:fputcsv() 期望参数 2 是数组,布尔值在 C:\server\xampp\htdocs\Gene\IMEXporter\include\IMEXporter_processor.php 中第 45 行给出警告:array_flip() 期望参数 1是数组,在 C:\server\xampp\htdocs\Gene\IMEXporter\include\IMEXporter_processor.php 第 47 行“成功”中给出的布尔值

标签: php jquery ajax


【解决方案1】:

找到有类似问题的人here

打开文件前添加一行

ini_set('auto_detect_line_endings',TRUE);

fgetcsv() 在到达文件末尾时返回布尔值“false”。来自 php 手册:

fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file.

参考:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    相关资源
    最近更新 更多