如何在 JavaScript 中请求网页

How to request a web page in JavaScript

在我的站点中,有一个无处不在的搜索栏,它是一个预输入小部件。该小部件有一个我目前正在尝试实现的 'selected' 回调。

在回调中判断是否需要在现有页面上进行AJAX请求,或者是否需要转到其他页面。我的问题是我无法在任何地方找到使用 POSTed 变量进行重定向的方法,例如 jQuery AJAX 请求。有什么方法可以通过发布的变量获得页面请求,从而完全刷新页面,例如单击普通超链接?

这是我的代码:

function getData(event, datum, dataset) {
    event.preventDefault();
    // get controller action portion of current url
    var Controller = '<?= preg_replace('/\/.*/', '', preg_replace('/\/.*\/web\//', '', Yii::$app->request->url)) ?>';
    var Key;
    // get key out of key-value pair - will either be 'game', 'developer' or 'publisher'
    for (var k in datum) {
        Key = k;
    }
    // if the controller action is the same as key, then the request is ajax
    // this works fine
    if (Key === Controller) {
        var req = $.ajax( {
            type: 'POST',
            url: 'getchilddata',
            data: { data: datum[Key] },
            })
        .done(function(data) {
           $('#display-div').html(data);
        })
        .fail(function() {
           console.log("Failed");
        })
    } else { // else we need to go to a page on a different controller action according to Key
        // this is the best i've got so far but want it to be better
        window.location.href = Key + '/datastream?q=' + datum[Key];
    }
}

实现此目的的唯一方法是创建一个隐藏输入的表单,因为您无法通过 Javascript 发送 post 变量,幸运的是有一个 Jquery plugin 可以保存你一些代码,但最后插件只是创建一个隐藏的表单并模拟通过 POST 发送表单的重定向,这是如何使用它:

 if (Key === Controller) {
    $.ajax( {...})
 } else { 
    $().redirect(Key + '/datastream, {'q': 'datum[Key]'});
 }

注意:您可以将方法(GET 或 POST)作为可选的第三个参数传递,POST 是默认值