javascript - 将变量从 onclick 传递到 ajax

标签 javascript php jquery ajax

我正在尝试将变量(区域)从 onclick 元素传递到 ajax 函数。 我正在使用 PHP、SQL 和插件 http://t4t5.github.io/sweetalert/

这是我在index.php 头部的代码

   <script type"text/javascript">
  function save(){
      $.ajax({
          type: "POST",
          url: "addlandtovisited.php",
          data: {region: region},
          success: function(data) {
              alert("Ajax save executed!");
          }
      });
  }
</script>

<script>
  jQuery(document).ready(function () {
    jQuery('#vmap').vectorMap({
      map: 'world_en',
      backgroundColor: '#333333',
      color: '#ffffff',
      hoverOpacity: 0.7,
      selectedColor: '#666666',
      enableZoom: true,
      showTooltip: true,
      scaleColors: ['#C8EEFF', '#006491'],
      values: sample_data,
      normalizeFunction: 'polynomial',

      onRegionClick: function (element, code, region) {
        var boton = "button";
        swal({   
              title: ''+region,  
              showCancelButton: true, 
              showConfirmButton: false, 
              text: '<a href="" onclick="save(region)">test</a>',

              html: true 
        });

      }
    });
  });
</script>

addlandtovisited.php:

<?php
if(isset($_POST['region'])){ 
?>

当我将字符串设置为ajax函数并从save(region)中删除该区域时,它工作正常:

data: {region: "TEST"},

text: '<a href="" onclick="save()">test</a>',

最佳答案

this thread表明 sweetalert 存储库存在一些问题。例如,我无法使 swal 在正文中渲染 html 文本。切换至sweetalert2并应用线程提到的补丁可能是个好主意。

我建议您使用确认按钮,而不是在 swal 正文中创建自己的链接。例如:

swal({
  title: '' + region,
  showCancelButton: true,
  showConfirmButton: true,
  confirmButtonText: "save",
  text: "anything",
  html: true

}, function() { // save button callback
  save(region);
});

不要忘记将 region 参数添加到 save() 方法中:save(region)

关于javascript - 将变量从 onclick 传递到 ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35253364/

相关文章:

javascript - 如何使用 onclick ="javascript:location.href"打开新选项卡?

javascript - 在每个 ng-repeat 之后添加元素

php - Vim 完成 + php 命名空间

javascript - 浏览包含 Node 模块但其中没有 .js 类的文件

javascript - fabricjs 路径的边界框偏移量

php - 如何为 Xdebug 3.0 版本设置 VSCode launch.json?

php - if-else block 中的解析错误意外}

javascript - 在 javascript 函数中使用 jquery animate

javascript - 如何获取DELETE请求参数

jquery - Angular 将页面转换为可下载或通过电子邮件发送的 html