【问题标题】:how to return as array in php function如何在php函数中以数组形式返回
【发布时间】:2017-07-04 06:29:22
【问题描述】:

我使用 laravel 5.4 和干预插件将图像作为 ajax 上传

我会在 php 控制器中上传图片,它会返回一个响应(文件名)。

从 php 中返回的变量是一个数组,但在 javascript 中它会变成字符串,我无法对其进行迭代

 public function upload(Request $request)
{
    $array = $request->file('image');
    $count = count($array);

    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[] = $rnd;
    }
    return $answer;
}

【问题讨论】:

标签: javascript php ajax laravel intervention


【解决方案1】:
public function upload(Request $request) {
    $answer=array();
    $array = $request->file('image');
    $count = count($array);
    $answer=array();
    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[$i] = $rnd;
    }
//here print $answer and check 
//you can also check $answer with function var_dump(); 
    echo json_encode($answer);
    die;
}

像这样解码这个数组

json_decode($json_array,true);

【讨论】:

  • 它仍然是 js 中的字符串。从 php 它的数组 ir json 正确但是当我在 js 中使用 xhr.responseText 得到它时它会变成字符串
  • 我从 js 代码解决了它。它应该从 javascript 转换为 json : var obj = JSON.parse(xhr.responseText);控制台.log(obj[1]); tnx
【解决方案2】:

试试这个,

return response()->json($answer);

【讨论】:

  • 请添加有问题的字符串结果
【解决方案3】:

尝试使用json_encode()

这将解决您的问题。

public function upload(Request $request)
{
    $answer=array();
    $array = $request->file('image');
    $count = count($array);

    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[] = $rnd;
    }
    echo json_encode($answer);
    die;
}

【讨论】:

  • echo json_encode(array("answer"=&gt;$answer)); die; 并在 ajax 代码中写入 dataType:'json' 以便在 ajax 成功响应中以 json 形式获得
猜你喜欢
  • 2010-12-05
  • 2020-02-20
  • 2014-05-01
  • 2017-04-04
  • 1970-01-01
  • 2020-09-27
  • 1970-01-01
  • 2019-11-30
  • 1970-01-01
相关资源
最近更新 更多