℡Wang Yan 2016-08-22 13:01 采纳率: 100%
浏览 64

Ajax转PHP和后CSV

Cant work out how to send results csv back as an object from Ajax , Its simple enough, the search works as expected but the results are sent back as a string i gather...

CSV

header1 , header2 , header3, header4, header5
Foo     ,  age-20 , male   , city NY , Cars  
Bar     ,  age-32 , female , city FL , Clothes
etc...

PHP

$search = $_POST['search'];
$row = 0;
$handle = fopen("items/data.csv", "r");
$complete = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if ($row == 0) {
            $row++;
        }else {
        for ($x=0; $x < 4; $x++) {  
             $se = $data[$x];
             if ($se == $search){
                 $num = count($data);
                 $row++;
                     for ($c=0; $c < $num; $c++) {  
                     $complete[] = $data[$c] ;  
                }
            }
    }
}
}
fclose($handle);       
echo json_encode($complete);

AJAX

$.ajax({    
url:'search.php',
type: 'POST',
data: {search: $('#search').val()},
success: function(data) {
 console.log(data);

},
error: function (error ,xml){
console.log(error);
}
}) 
}   

Im having a hard time trying to use this information that is returning, I deally i would like it as an array();

 **Returned String Output**

["Bar","Age-32","Female","city FL","Clothes"]

Thanks

  • 写回答

2条回答 默认 最新

  • larry*wei 2016-08-22 13:09
    关注

    The first thing that comes to mind is $.ajax having a dataType attribute that allows you to force an expected data type, in this case json.

    Note that - as per the documentation - you don't need to define dataType if the MIME type is set correctly on the server side. You can use PHP's header function to achieve this: header('Content-Type: application/json').

    Read the official documentation here.

    $.ajax({
        url: 'search.php',
        type: 'POST',
        dataType: 'json',
        data: { search: $('#search').val() },
        success: function(data) {
            console.log(data);
        },
        error: function (error, xml) {
            console.log(error);
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况