【问题标题】:How to write @if in ajax if im using laravel如果我使用 laravel,如何在 ajax 中编写 @if
【发布时间】:2018-03-30 14:46:49
【问题描述】:

如果我使用 Laravel 和你看到的 laravel 中的代码,我需要帮助如何在 javascript 中编写 @if 角色,但我想在 ajax 部分编写相同的代码

Laravel 代码:

 <td class="text-center">@if ($post->adver_position==0) TOP @endif @if ($post->adver_position==1) RIGHT @endif @if ($post->adver_position==2) LEFT @endif @if ($post->adver_position==3) BOTTOM @endif</td>

阿贾克斯:

      $('.item' + data.id).replaceWith("<tr class='item" + data.id + "'><td  class='col1'>" + data.id + "</td><td><img src='images/" + data.adver_photo + "'style='width: 50%;margin-left: 35px;border-radius: 3px;border: 1px solid #1a2732;' /></td><td>" + data.adver_title + "</td>"

【问题讨论】:

    标签: javascript php ajax laravel


    【解决方案1】:

    您需要使用 javascript,而不是 laravel 模板语法。 Laravel 是一个 PHP 框架,所以它在服务器端呈现。 Javascript 是客户端,它是您向服务器发出异步请求的地方。

    你应该这样做(我不知道 jQuery ajax 语法)

    $.ajax({
      done: function (post) {
        const pos = post.adver_position
        var textPos
    
        if (pos == 0)
          textPos = 'TOP'
        else if (pos == 1)
          textPos = 'RIGHT'
        else if (pos == 2)
          textPos = 'LEFT'
        else
          textPos = 'BOTTOM'
    
        /* Place your DOM handling code here */
      }
    })
    

    不过,您的代码有点糟糕。我建议你尝试一些 js 框架来构建 UI,其中有很多(例如 React、Angular、Vue.js)。

    【讨论】:

      【解决方案2】:

      您不能从客户端使用刀片,但您的问题的解决方案将是下一个。您可以构建 replaceWith() 函数内部的字符串并从 java 脚本中进行比较,例如:

        var content = "<tr class='item" + data.id + "'> "
                      +  "<td  class='col1'>" + data.id + "</td> "
                      +  "<td><img src='images/" + data.adver_photo + "'style='width: 50%;margin-left: 35px;border-radius: 3px;border: 1px solid #1a2732;' /> </td>" 
                      +  "<td>" + data.adver_title + "</td>"
                      +  "<td> ";
      
        switch(data.adver_position) {
          case 0:
              content = content + "TOP";
              break;
          case 1:
              content = content + "RIGHT";
              break;
          case 2:
              content = content + "LEFT";
              break;
          case 3:
              content = content + "BOTTOM";
              break;
          }
      
          content = content + "</td> </tr>"
      
      
           $('.item' + data.id).replaceWith(content);
      

      【讨论】:

      • 如何添加 style=text-align:center;每种情况?
      猜你喜欢
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多