【问题标题】:Simple Ajax call with result handler does not work带有结果处理程序的简单 Ajax 调用不起作用
【发布时间】:2018-11-05 10:49:08
【问题描述】:

我得到了这个 JS:

<script>
jQuery(document).ready(function(){ // we wait until DOM is ready
    jQuery('#veranstort').change(function(){ // fire when input is filled

        origin = "55767 Schwollen";
        destination = "13509 Berlin";

        jQuery.ajax({ // we build the AJAX request
                method:"POST", 
                url:"index.php?option=com_rsform&formId=6&action=ajax", 
                data: {origin, destination},
                success: function(results) {
                    console.log("results: " + results);

                }
        });
    });
})
</script>

触发这个 php 脚本:

$action = JRequest::getWord('action'); // we will need a parameter to run the script
if ($action == "ajax") { // if condition is met, run the script

    $origin = $_POST['origin']; // get the origin
    $destination = $_POST['destination']; // get the destination
    var_dump("destination: ".$destination); // this gives me NULL!!

    $distance = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin."&destinations=".$destination."&key=GMAPSKEY"); // build the URL according to the API

    $distance = json_decode($distance); // decode the response from JSON

    print_r($distance->rows[0]->elements[0]->distance->text);die(); // print the result so we can catch it in the AJAX call

}

这已经工作了一段时间,但现在不行了。我无法访问 php 中的目标值或原始值。我做错了什么?

【问题讨论】:

  • 尝试像这样data: {"origin": origin, "destination": destination}, 发送您的数据。您尝试将数据作为没有键的对象发送。基本上你发送{"55767 Schwollen","13509 Berlin"},它不是一个propper 对象也不是一个数组。但是在 PHP 中,您尝试访问像 $_POST['origin']; 这样的不存在的键。不知道以前是如何工作的。
  • @Honkalonkalooooohhh - 错误,不。你似乎有点落后于现代 JavaScript。问题中的语法很好。 jsbin.com/fivogovola/1/edit?js,console
  • 我能想到的唯一可能会产生您所描述的结果的事情是,如果您在某处有一个 ajaxSetup 呼叫会破坏您的数据发送方式。但这不在问题之列。您需要提供minimal reproducible example
  • 发送Ajax请求时能否贴出Request header的截图,如果请求头中有数据对象,假设您使用RSform组件,Joomla组件肯定会出现问题。
  • 表单数据已提交:imageshack.com/a/img921/4447/Mjjqr1.jpg 是的,可能是 rsforms 问题..

标签: javascript php ajax post google-distancematrix-api


【解决方案1】:

错误来自 URL 中缺少的 /。它被重定向了,POST 数据在这个过程中丢失了。

正确的网址:

url:"/index.php?option=com_rsform&formId=6&action=ajax"

【讨论】:

    【解决方案2】:

    脚本文件没问题。请更改ajax文件条件。

    $action = $_GET['action'];
    
    if ($action == "ajax") { // if condition is met, run the script
    
    
         //// Here process your code
    }
    

    【讨论】:

    • 他们说问题在于访问destinationorigin,而不是action
    • 该屏幕截图似乎与您的答案完全无关。
    • 在 ajax 文件中,我返回了请求 POST 值。在控制台中显示帖子值。
    • 这只是意味着您无法重现该问题。
    • @VinothRaja — 如前所述,您建议的更改不会影响问题。如果他们这样做了,那么问题将是“PHP 永远不会进入 IF 语句”而不是“PHP 确实 进入 IF 语句但 POST 值为 null
    猜你喜欢
    • 2011-12-30
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多