通过Ajax返回存储过程输出

时间:2019-04-17 20:13:13

标签: javascript ajax laravel stored-procedures pdo

我目前有一个工作过程,在刀片中进行ajax调用,该调用通过控制器进行调用,并且该函数使用PDO命中存储过程调用。此调用成功,并且我的存储过程正确执行/插入,并设置为返回我的输出。我现在唯一的问题是:

如何获取存储过程的输出并将其传递回刀片服务器以进行隐藏输入?没有页面刷新,因此当AJAX调用成功时,我想将服务文件中的输出放入刀片中的隐藏输入中。我该怎么做呢?

刀片:

$.ajax({

   type:'POST',
   url:'campaigns/createCampaign',
   data:{campaignName:campaignName, attribute:attribute},
    _token: '{{ csrf_token() }}',
   success:function(data){
        intro_modal.hide();
   }
});

控制器:

public function createCampaign(Request $request)
{
    $campaignName = $request->campaignName;
    $attribute = $request->attribute;

    $campaignService = new CampaignService();
    $createCampaign = $campaignService->createCampaign($campaignName, (int) $attribute);

    //return response()->$campaignService;
}

服务:

function createCampaign($campaignName, $attribute){

    $stmt = \DB::connection('odbc')->getPdo()->prepare('CALL PROCEDURES.INSERT_CAMPAIGN(?,?,?)');

    $stmt->bindValue(1,$campaignName, PDO::PARAM_STR);
    $stmt->bindValue(2,$attribute, $attribute==0 ? PDO::PARAM_NULL : PDO::PARAM_INT);
    $stmt->bindParam(3,$out2, PDO::PARAM_INT);

    $stmt->execute();

}

1 个答案:

答案 0 :(得分:1)

在您的 createCampaign

function createCampaign($campaignName, $attribute){

    $stmt = \DB::connection('odbc')->getPdo()->prepare('CALL PROCEDURES.INSERT_CAMPAIGN(?,?,?)');

    $stmt->bindValue(1,$campaignName, PDO::PARAM_STR);
    $stmt->bindValue(2,$attribute, $attribute==0 ? PDO::PARAM_NULL : PDO::PARAM_INT);
    $stmt->bindParam(3,$out2, PDO::PARAM_INT);
    $stmt->execute();

    return $out2;
}

在您的控制器

使用这些类:

use Illuminate\Support\Facades\Response;
use Illuminate\Http\Response as HttpResponse;

返回JSON响应:

public function createCampaign(Request $request)
{
    $campaignName = $request->campaignName;
    $attribute = $request->attribute;

    $campaignService = new CampaignService();
    $createdCampaignId = $campaignService->createCampaign($campaignName, (int) $attribute);

    return Response::json(["campaign_id" => $createdCampaignId)
            ->setStatusCode(HttpResponse::HTTP_OK);
}

在您的刀片模板

$.ajax({

   type:'POST',
   url:'campaigns/createCampaign',
   data:{campaignName:campaignName, attribute:attribute},
    _token: '{{ csrf_token() }}',
   success:function(data){
        intro_modal.hide();
       // data.campaign_id will contains the new campain id
   }
});

例如,您只需要在data.campaign_id后面插入jQuery的值即可。