【问题标题】:Send Request In Laravel Using AJAX GET Method在 Laravel 中使用 AJAX GET 方法发送请求
【发布时间】:2020-12-07 11:01:01
【问题描述】:

想通过 AJAX 访问 Show 函数数据,但是当我在路由中传递 id 变量时返回错误

控制器

public function show($id)
{
    $features['UnitFeatures'] = UnitFeatures::find($id);
    return $features;
}

查看刀片文件

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

var feature_id = $('#unitFeatures').val();

$.ajax({
    url: '{{ route('unitfeatures.show',feature_id) }}', // error in this line when i pass feature_id value to route
    type: 'GET',
    dataType: 'json',
    success: function(response){
      console.log(response);
     }
    });
  });

请给我一个解决方案

【问题讨论】:

标签: javascript php jquery laravel laravel-blade


【解决方案1】:

问题是您无法在{{}} PHP 代码中访问 JS 变量。 您必须在 JS 代码中手动获取路由 uri 并替换占位符。

您可以使用以下代码获取 Route 的 URI: \Route::getRoutes()->getByName('unitfeatures.show ')->uri

这会将 uri 作为字符串返回:/sometext/{id}

现在您可以使用 str.replace() 或任何您喜欢的函数将 {id} 替换为 feature_id

var feature_id = $('#unitFeatures').val();
var origUrl = '{{ \Route::getRoutes()->getByName('unitfeatures.show ')->uri}}';
$.ajax({
    url: origUrl.replace('{id}', feature_id), 
    type: 'GET',
    dataType: 'json',
    success: function(response){
      console.log(response);
     }
    });
  });

【讨论】:

  • 我也会使用路由 url。但问题是我使用 Route::resource('unitfeatures','FeaturesController') 所以它会自动生成 SHOW 函数。我称之为 unitfeatures.show
  • 我知道问题所在。我没有对此进行任何研究,但也许有一种方法可以让您访问原始命名路由。
  • @MUSTOFA 是否有效或您是否找到了其他答案?
【解决方案2】:

您在 PHP 代码中使用 Javascript 变量的问题您可以在执行 PHP 代码后使用 Javascript 变量,将其视为字符串。

$.ajax({
    url: "{{ route('unitfeatures.show') }}"+'/'+feature_id,
    type: 'GET',
    dataType: 'json',
    success: function(response){
      console.log(response);
     }
    });
  });

【讨论】:

  • 这行不通,因为route('unitfeatures.show', $id) 需要$id 来生成路由
  • @Aless55 route('unitfeatures.show', $id) 将生成与http://127.0.0.1:8000/your_url/id 相同的 URL,表明您可以按照我回答的方式进行操作,我已经测试过它的工作正常。
  • 是的,但是这个{{ route('unitfeatures.show') }}会给你一个错误
  • 您需要在路由文件Route::get('/your_url', 'controller@function')->name('unitfeatures.show'); 中定义它,然后{{ route('unitfeatures.show') }} 才能正常工作。
  • @Aless55 请查看 laravel 文档以了解 Generating URLs To Named Routes
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
  • 2015-07-17
  • 2015-09-07
  • 1970-01-01
相关资源
最近更新 更多