weixin_33712881 2017-03-26 03:34 采纳率: 0%
浏览 274

在Laravel中调用Ajax路由

view
==========
$('#searchstudent').on('click',function(){
    event.preventDefault();
    var formdata = $('#searchform').serialize();
    console.log(formdata);
         $.ajax({
            url:'/test',
            type:'post', 
            dataType:'json', 
            data : formdata ,
            success : function(data){
                console.log('hey'+data);
            }
         });
      });

route

Route::post('/test', ['as'=>'test','uses'=>'HomeController@test']);

controller

use Illuminate\Http\Response;

public function test(Request $request){
    return response()->json(['name' => 'praveen', 'country' => 'SL']);
 }

Issues I Face

1)Currently i am in this url

http://localhost/blog/allocatestudent/1

from this url only my view is rendered and from here i am calling above mentioned ajax function

Error message i got from console

POST http://localhost/test 404 (Not Found) 

What i tried to change the url in ajax function like below

url:'test' instead of url:'/test'

and in my route

Route::post('test', ['as'=>'test','uses'=>'HomeController@test']);

so i am getting another error message as

POST http://localhost/blog/allocatestudent/test 405 (Method Not Allowed) 

Anybody can tell me where i am doing wrong?...

  • 写回答

1条回答 默认 最新

  • weixin_33726318 2017-03-26 04:02
    关注

    When you specify the AJAX URL with an leading slash (like /test), it will handle the request as absolute path (like yourdomain.com/test), in your case localhost/test.

    Change the URL to the whole absolute path, but without your domain: /blog/allocatestudent/test

    AJAX will interpret it as localhost/blog/allocatestudent/test

    The best (durable and DRY) solution would be to create a function that returns the url with the fixed path before.

    var BASE_URL = '/blog';
    
    function getUrl(url) {
        return BASE_URL.concat(url);
    }
    
    console.log(getUrl("/allocatestudent/test")); //returns "/blogallocatestudent/test
    
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵