【问题标题】:Is this the correct syntax to send a GET request URL?这是发送 GET 请求 URL 的正确语法吗?
【发布时间】:2019-05-28 03:24:17
【问题描述】:

向我的表中插入值我尝试了这个 GET xmlhttprequest 对象。 我在 URL 中的语法是否正确?它不工作。

document.getElementById('allsubmit').addEventListener('click',sendPost);
  var com = document.getElementById('inputcompany').value;
  var cat = document.getElementById('selectCategory').value;
  var subcat = document.getElementById('selectsubCategory').value;
  var descrip = document.getElementById('textdescription').value;
  var exp = document.getElementById('datepicker').value;

  function sendPost() {
   var xhr = new XMLHttpRequest();
    xhr.open('GET',"addingthevacancy.php?company='"+com+"'?category='"+cat+"'?subcategory='"+subcat+"'?description='"+descrip+"'?expdate='"+exp,true);

xhr.onprogress = function() {
      //
}

xhr.onload = function() {
    console.log("Processed..."+xhr.readystate);
    console.log(this.responseText);
}

xhr.send();
}

我不知道这里出了什么问题。

【问题讨论】:

  • 定义“它不起作用”:请参阅How to Ask 页面。
  • 当你想传入多个 get 参数时,你需要像这样格式化它:url?company=''&category=''
  • URL 中的参数? 开头,但每个参数应与下一个参数以& 分隔,而不是?
  • 您还应该使用encodeURIComponent()对参数进行正确编码,以防它们包含在URL中具有特殊含义的字符。
  • 还建议您在进行更改时使用POST 而不是GETGET 应该只用于检索。

标签: javascript ajax http


【解决方案1】:

几个问题:

  1. 参数必须用&分隔,而不是?
  2. URL 参数不需要用引号引起来。
  3. 参数应该使用encodeURIComponent()进行编码。
  4. 您需要在sendPost()函数中获取输入的值;您的代码在页面首次加载时设置变量,而不是在用户提交时设置。
  5. 如果按钮是提交按钮,需要调用e.preventDefault()覆盖默认提交。

一般不建议将GET 用于在服务器上进行更改的请求,POST 通常应该用于这些类型的请求。浏览器缓存GET请求,所以如果你真的需要这样做,你应该添加一个cache-buster参数(一个额外的,未使用的参数,包含一个随机字符串或每次更改的时间戳,只是为了防止URL匹配缓存网址)。

document.getElementById('allsubmit').addEventListener('click', sendPost);

function sendPost(e) {
  e.preventDefault();
  var com = encodeURIComponent(document.getElementById('inputcompany').value);
  var cat = encodeURIComponent(document.getElementById('selectCategory').value);
  var subcat = encodeURIComponent(document.getElementById('selectsubCategory').value);
  var descrip = encodeURIComponent(document.getElementById('textdescription').value);
  var exp = encodeURIComponent(document.getElementById('datepicker').value);

  var xhr = new XMLHttpRequest();
  xhr.open('GET', "addingthevacancy.php?company=" + com + "&category='" + cat + "&subcategory=" + subcat + "&description=" + descrip + "&expdate=" + exp, true);

  xhr.onprogress = function() {
    //
  }

  xhr.onload = function() {
    console.log("Processed..." + xhr.readystate);
    console.log(this.responseText);
  }

  xhr.send();
}

【讨论】:

    猜你喜欢
    • 2020-09-30
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多