简体   繁体   English

如何将参数传递给url

[英]how to pass parameters to url

I'm trying to pass parameters to a URL and get them into a controller function: in an anchor onclick I passed the value to a javascript function. 我正在尝试将参数传递给URL并将其传递给控制器​​函数:在锚点onclick我将值传递给了javascript函数。

This is the onclick anchor: 这是onclick锚点:

<a href="" onclick="change_lang('<?=base_url()?>home/change_lang','en')">English</a>

and this is the javascript function: 这是javascript函数:

function change_lang(page,str)
{
  var url=page;
  var params='?lang='+str;

  makerequest_sp(url, params);
}

and this is the controller function: 这是控制器功能:

public function change_lang()
{
  $lang=$this->input->Get('lang');

  if(!isset($lang))
  {
    $this->session->set_userdata('lang',"en"); 
  }
  else
  {
    $this->session->set_userdata('lang',$lang); 
  }

  redirect(base_url());
}

and this makerequest_sp function: 这个makerequest_sp函数:

  function makerequest_sp(serverPage, params, objID)
{ 
    var xmlhttp_sp = getXMLHttp();
    //set url
    var url = serverPage;

    //set xml method to POST
    xmlhttp_sp.open("POST", url, true);
    //Send the proper header information along with the request
    xmlhttp_sp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
    xmlhttp_sp.setRequestHeader("Content-length", params.length);
    xmlhttp_sp.setRequestHeader("Connection", "close");

    xmlhttp_sp.onreadystatechange = function() {//Call a function when the state changes.

        if(xmlhttp_sp.readyState == 4 && xmlhttp_sp.status == 200) {
            document.getElementById(objID).innerHTML = xmlhttp_sp.responseText;
        }
    }
    //send parameters
    xmlhttp_sp.send(params);    

}

But I cant access to passed parameters. 但是我无法访问传递的参数。

You're doing an AJAX request. 您正在执行AJAX请求。 I'm guessing you're wondering why the redirect doesn't make the browser redirect? 我猜你在想为什么redirect不能使浏览器重定向?

This is because the AJAX request is getting the redirect, not the page. 这是因为AJAX请求正在获取重定向,而不是页面。

Instead of sending a redirect header you can pass back the URL the page should redirect to, or in case you know the URL already you can just redirect right away: 无需发送重定向标头,您可以传递页面应重定向到的URL,或者如果您已经知道 URL,则可以立即重定向:

makerequest_sp(/* .. */).done(function () {
    document.location.href = url;
});

// using Promise assumption for ajax request

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM