首页 > 解决方案 > 传递给 Symfony\Component\HttpFoundation\Response::setContent() 的 TypeError 参数 1 必须是字符串类型或 null,给定对象,

问题描述

我使用下面的代码,我需要time()从服务器获取,我在 laravel 中使用了 PUSHER和 QUEUE

我使用具有3 个 div 的html(刀片文件),如下所示,


                <div id="divId1">0</div>

                <div id="divId2">0</div>

                <div id="divId3">0</div>

每个0div 中的 替换time()为 Controller 中的。

  1. 控制器
class TimeController extends Controller
{
    public function getTime($divId = null)
    {

     $res = dispatch(new TimeChange());
     return $res;
     dd($res);
    }
}

js 文件中

$(document).ready(function(){
 $.ajaxSetup({
     headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

  document.querySelectorAll('*').forEach(function(node) {
    var data = '';
    ajax = $.ajax({
      url: '/getTime/' . node,
      method: 'get',
      success: function(data) {
         //parse the server side response
         console.log(data);
      }
    });
   });
});

 var pusher = new Pusher('xxxxxxxxxxxxxxx', {
        cluster: 'eu',
        encrypted: true
      })
      var channel = pusher.subscribe('time-updated');
   // Binding a function to a Event
     channel.bind('App\Events\TimeUpdated', function(data){
     console.log(data);
 });

事件文件

class TimeUpdated implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

     public $timechanged, $divID;
    public function __construct($divID, $timechanged)
    {
       $this->timechanged = $timechanged;
       $this->divID = $divID;
    }

   
    public function broadcastOn()
    {
        return new Channel('time-updated');
    }
    
}

路由.php

Route::get('/getTime/{id}', 'App\Http\Controllers\TimeController@getTime');
  1. 队列时间变化
<?php

namespace App\Jobs;
use App\Events\TimeUpdated;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class TimeChange implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct()
    {
        //
    }

    public function handle()
    {
         $result = event(new TimeUpdated($divId, 'time()'));

    }
}

在浏览器中,当我将 URL 传递为www.sample.test/getTime/3时,出现以下错误。

TypeError
Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent() must be of the type string or null, object given, 

当我跑步时php artisan queue:work

[2021-05-10 06:22:51][1] Processing: App\Jobs\TimeChange
[2021-05-10 06:22:51][1] Failed:     App\Jobs\TimeChange
[2021-05-10 06:22:51][2] Processing: App\Jobs\TimeChange
[2021-05-10 06:22:51][2] Failed:     App\Jobs\TimeChange
[2021-05-10 06:26:13][3] Processing: App\Jobs\TimeChange
[2021-05-10 06:26:13][3] Failed:     App\Jobs\TimeChange

有人可以帮忙吗?

标签: jquerylaravelpusher

解决方案


推荐阅读