javascript - 使用 jQuery 获取 url 并提取 url 段

标签 javascript jquery ajax url

在具有类别列表的网页上,每个类别标题都以这种格式链接:http://localhost/admin/category/unpublish/2

我写了下面的js代码,试图捕获url和段'unpublish'(action)和'2'(id),并且需要将请求发送到http://localhost/admin/类别

$('#statusChanges a').click(function(evt) { // use the click event of hyperlinks
  evt.preventDefault();
  var url = $(location).attr('href');
  // var action = url.segment(3);  /*JS console complains that url.segment() method undefined! */
  // var id = url.segment(4);
  $.ajax({
    type: "GET",
    url: $(location).attr('href'),
    dat: '',
    /* do I need to fill the data with json data: {"action": "unpublish, "id": 2 } ? but I don't know how to get the segments */
    success: function(data) {
      $('.statusSuccess').text('success!');
    },
    error: function(data) {
      $('.statusSuccess').text('error!');
    }
  });
}); // end of status change

最佳答案

试试这个

var url = $(location).attr('href').split("/").splice(0, 5).join("/");

更新答案:

使用 this 对象获取当前 anchor 链接,见下文

$(this).attr('href')

关于javascript - 使用 jQuery 获取 url 并提取 url 段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24481918/

相关文章:

javascript - jQuery 在 ajax 成功回调中被忽略

python - 对动态设置的 MultipleChoiceField 进行验证,该字段最初为空?

javascript - 如何在 jquery post 中返回数据?

javascript - 如何使用 Next/Head 渲染脚本

javascript - 禁用滚动但使用 JavaScript 捕获滚动数据?

php - 多张图片上传、全部显示、全部拖放

php - laravel webview 中的 Ajax 文件上传不起作用

javascript - jquery中的文件拖放事件

javascript - 如何使用 jquery 航点动态生成航点?

jquery - 无法在 jQuery css 方法中设置负边距