使用AJAX GET请求将<option>标记的值传递给URL

时间:2017-12-29 15:29:56

标签: javascript ajax html-select

每当用户选择一个选项时,我想将选项的值传递给URL。例如,这些是选项:

  • 选项1
  • 选项2
  • 选项3

这是网址:http://example.com/products

当他在这3个中选择一个选项时,URL会变为:http://example.com/products?option = option1

我为此尝试了vanilla Javascript XMLHttpRequest,这是我的代码:

function ajaxFormValidate(_method, _url, _callback, _fallback, _sendItem) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState < 4) {
            return;
        }
        if(xmlHttp.status !== 200) {
            _fallback(xmlHttp.response);
            return;
        }
        if(xmlHttp.readyState === 4) {
            _callback(xmlHttp.response);
        }
    };
    xmlHttp.open(_method, _url, true);
    xmlHttp.send(_sendItem);
} //Set a function for AJAX Request
//Actual performance
window.addEventListener('load', function(){
    var _sort = document.getElementById('sort'), _filter = document.getElementById('filter'); //Get the elements
    _sort.addEventListener('change', function(){ //If the value of the field changes
        var _frmData = new FormData(); //Create a new FormData object
        _frmData.append('sort', _sort.value); //Append the value to this object
        ajaxFormValidate('GET', location.href, function(response){
            //Perform the redirection here (without reloading the page)
        }, function(response){
            alert("Request cannot be sent!");
        }, _frmData);
    }, false);
});

最近,我对此没有任何想法。任何帮助表示赞赏。感谢

1 个答案:

答案 0 :(得分:0)

这是在纯Javascript中使用GET的好方法:

var ajax = new XMLHttpRequest();

ajax.open("GET", "example.com/products.php?option=YOUR OPTION VALUE GOES HERE", true);


ajax.send();


ajax.onreadystatechange = function() {


    if (ajax.readyState == 4 && ajax.status == 200) {

        var data = ajax.responseText;

        console.log(data);
    }
}

这是jQuery方式(我的首选方法)

var myOption = $('.your-elenet-calss-name').val();
var myurl = "http://example.com/products.php";
var dataString="&option="+myOption+"&check=";
$.ajax({
type: "GET",
url: myurl,
data:dataString,
crossDomain: true,
cache: false,
beforeSend: function(){//Do some stuff here. Example: you can show a preloader///},
success: function(data){

if(data =='success'){

alert('done deal...');

}


}
});