【问题标题】:How to avoid php getting vuejs params as string when it is undefined or null如何避免 php 在未定义或 null 时将 vuejs 参数作为字符串获取
【发布时间】:2022-11-18 08:26:03
【问题描述】:

这可能是一个愚蠢的问题或被问过很多次(如果是这样,请使用现有链接回答,我将关闭此帖子)。

让我们以 laravel 为例,当在路由中发送模型 id 时,在 php 中一切正常。但是当路由必须在 Vuejs 中定义为 null(或未定义)的可选参数时,Php 将此参数作为字符串获取。

//vuejs in methods:
myFunction(id1, id2 = null) {
  axios.post(`/api/model1/${id1}/model2/${id2}`)
    .then((response) => {
        console.log(response);
    })
    .catch(err => {
        console.log(err);
    });
 },

//Laravel routes/api.php for my api
Route::post('model1/{id}/model2/{id2}', 'SomeController@doThis');

示例:myapi/model1/{id1}/model2/{id2} 和 myapi/model1/987/model2/null

所以我在这里得到 model2 的“null”。 (有时根据情况是'undefined')

什么是更好的处理方法? 没有为我的参数添加正则表达式?因为我不需要第一个参数 id1 的正则表达式。

我尝试了很多次处理它,但似乎我总是时不时地回到这个问题上。我需要永远记住这一点。

【问题讨论】:

  • 这可能是由您用来生成要调用的 URL 的代码引起的。你能分享那个代码吗?

标签: php laravel vue.js parameters url-parameters


【解决方案1】:

构建 URL 时应进行空值检查:

//vuejs in methods:
myFunction(id1, id2 = null) {
  axios.post(`/api/model1/${id1}/model2${id2 ? `/${id2}` : ''}`)
    .then((response) => {
        console.log(response);
    })
    .catch(err => {
        console.log(err);
    });
 },

【讨论】:

    猜你喜欢
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    相关资源
    最近更新 更多