2

我试图从 javascript 将参数传递给 servlet:

function selectHandler() {
  var selection = table.getChart().getSelection()[0];
  var topping = data.getValue(selection.row, 0);
  var answer=confirm("Delete "+topping+"?");
  if(answer){
    document.location.href="/item?_method=delete&id="+topping;
    alert(topping+" has been deleted");
    location.reload();
  }
  else return false;
}

这些值正在传递给 servlet,并且当我使用firefox时工作正常,因为我将 url 获取为:http://XXXXXXX/item?_method=delete&id=xxxx 但是当我使用chrome时,发送的 URL 是http://XXXXXXX/item. 因为价值观没有通过!!我也试过window.location.href没有改变。可能是什么问题?

4

1 回答 1

3

您需要的是 ajax 调用或说 XMLHttpRequest 如下:

<script type="text/javascript">
    function doAjax () {
        var request,
            selection = table.getChart().getSelection()[0],
            topping = data.getValue(selection.row, 0),
            answer=confirm("Delete "+topping+"?");

        if (answer && (request = getXmlHttpRequest())) {
            // post request, add getTime to prevent cache
            request.open('POST', "item?_method=delete&id="+topping+'&time='+new Date().getTime());
            request.send(null);
            request.onreadystatechange = function() {
                if(request.readyState === 4) {
                    // success
                    if(request.status === 200) {
                        // do what you want with the content responded by servlet
                        var content = request.responseText;
                    } else if(request.status === 400 || request.status === 500) {
                        // error handling as needed
                        document.location.href = 'index.jsp';
                    }
                }
            };
        }
    }
    // get XMLHttpRequest object
    function getXmlHttpRequest () {
        if (window.XMLHttpRequest
            && (window.location.protocol !== 'file:' 
            || !window.ActiveXObject))
            return new XMLHttpRequest();
        try {
            return new ActiveXObject('Microsoft.XMLHTTP');
        } catch(e) {
            throw new Error('XMLHttpRequest not supported');
        }
    }
</script>

您也可以通过 jquery 轻松完成,

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />
<script type="text/javascript">
    function doAjax () {
        ...
        $.ajax({
            url: "item?_method=delete&id="+topping+'&time='+new Date().getTime()),
            type: "post",
            // callback handler that will be called on success
            success: function(response, textStatus, jqXHR){
                // log a message to the console
                console.log("It worked!");
                // do what you want with the content responded by servlet
            }
        });
    }
</script>

参考:jQuery.ajax()

于 2013-01-25T07:33:50.270 回答