如何从URL参数中获取数据?

时间:2015-07-16 19:37:34

标签: javascript jquery

我需要2个信息才能进行AJAX调用。

  1. assessmentId
  2. classroomId

    $。AJAX({

    @Override
    public EngineOptions onCreateEngineOptions()
    {
       camera = new BoundCamera(0, 0, GameWidth, GameHeight);
       EngineOptions engineOptions = new EngineOptions(true,ScreenOrientation.PORTRAIT_FIXED, new FillResolutionPolicy(), this.camera);
       engineOptions.getAudioOptions().setNeedsMusic(true).setNeedsSound(true);
       engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
       return engineOptions;
    }
    
  3. 我想从网址参数中获取它们。

    url: "/rest/report/assignment", type: "POST", dataType: "json", data: { assessmentId: "206a9246-ce83-412b-b8ad-6b3e28be44e3", classroomId: "722bfadb-9774-4d59-9a47-89ac9a7a8f9a" },

    我需要在某处使用http://localhost:8080/BIM//teacher/reports/section-exercise/assignment?assessmentId=4d8d208e-8f71-4255-b54a-4c87a002314d&assessmentType=HOMEWORK&classroomId=722bfadb-9774-4d59-9a47-89ac9a7a8f9a&courseContentId=fd51fe9b-62ed-48f9-a6d8-5635f24964d6吗?

    对此的任何指示都将非常感谢!

1 个答案:

答案 0 :(得分:1)

如果您只想从URL中获取参数,可以使用以下函数简单地解析URL:

function parseUrl(url) {
  var urlParamSplit = url.split("?");

  if(urlParamSplit.length !== 2) return "InvalidUrlNoParamsSet";

  var paramsList = urlParamSplit[1].split("&");
  if(paramsList.length < 1) return "InvalidUrlNoParamsFound";

  var paramsObj = {};
  paramsList.forEach(function(item){
    var keyValueArray = item.split("=");
    paramsObj[keyValueArray[0]] = keyValueArray[1];
  });

  return paramsObj;
}

仅当参数名称永不更改且始终设置了某些参数时,才可以执行此操作。

您的ajax调用可能如下例所示:

var params = parseUrl("http://localhost:8080/BIM//teacher/reports/section-exercise/assignment?assessmentId=4d8d208e-8f71-4255-b54a-4c87a002314d&assessmentType=HOMEWORK&classroomId=722bfadb-9774-4d59-9a47-89ac9a7a8f9a&courseContentId=fd51fe9b-62ed-48f9-a6d8-5635f24964d6");
// your ajax call could look like this:
$.ajax({
  url: "/BIM/rest/report/assignment",
  type: "POST",
  dataType: "json",
  data: {
      assessmentId: params.assessmentId,
      classroomId: params.classroomId
  }, 
  // ... further settings and callbacks ...
});

您可以通过location.href获取网站的当前网址。因此,您可以调用var params = parseUrl(location.href);来解析当前的网址参数。

而且您不需要添加隐藏的输入字段。