【问题标题】:OctoberCms How to pass ajax response to javascript functionOctoberCms 如何将ajax响应传递给javascript函数
【发布时间】:2019-06-23 02:59:55
【问题描述】:

我在我的组件 html 文件中创建了一个表单,当我提交一个表单时,一个 ajax 调用会触发我在组件中定义的操作。到目前为止,我的代码运行良好,我得到了响应。但现在我希望将响应传递给我在组件 htm 文件中创建的 javscript 函数。

function markAddresses(addresses) {
geocoder = new google.maps.Geocoder();
addresses.forEach(address => {
  geocoder.geocode({'address': address}, function(results, status) {
   if (status === 'OK') {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({map: map,position: results[0].geometry.location});
       } else {
      alert('Geocode was not successful for the following reason: ' + status);
   }
  });
  })

}

我想通过 markAddresses(response) 之类的回复

<form method="post" data-request="onSend">
<div class="col-md-5">
    <input type="text" name="location" class="form-control">
</div>
<div class="col-md-2">

    <select name="service[]" id="services" class="form-control">&nbsp;
        {% for client in records %}
            <option value="{{ client.service }}">{{ client.service }}</option>
        {% endfor %}
    </select>
</div>
<div class="col-md-2">
    <select name="area[]" id="search" class="form-control" >&nbsp;
        {% for client in records %}
            <option value="{{ client.area }}">{{ client.area }} Miles</option>
        {% endfor %}
    </select>
</div>
<div class="col-md-3">
    <input type="submit" value="Looks for Shops" class="red-btn btn btn-default">
    <a class="location-view" href="#">View all Shops</a>
</div>

这就是我的 Ajax 的工作方式。我认为是使用 octobercms Ajax 框架

【问题讨论】:

  • 你能分享你的ajax请求表单标记,你是如何进行ajax调用的
  • @HardikSatasiya 分享

标签: javascript ajax laravel octobercms october-partial


【解决方案1】:

您可以使用data-attributes-api

<form method="post" 
      data-request="onSend" 
      data-request-success="markAddresses(data)"
      <!--    ^-- this one -->
>
....
</form>

确保markAddresses 是全局函数,您可以全局访问它。 data 是处理程序的返回值。

如果你的处理程序看起来像这样

function onSend() {
    return ['test' => 'data'];
}

它将像下面markAddresses中的对象作为变量data传递

console.log(data); // output : { "test": "data" }

如有疑问请评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 2018-09-01
    相关资源
    最近更新 更多