HTML& REST(动态" id"在链接中)

时间:2016-05-26 11:06:12

标签: html

我使用HTML作为REST客户端。我需要将表单数据发送到服务器。 在服务器端(用java实现),我的POST(我使用POST更新我的表)方法的路径类似于:@Path(" http://www.something.com/ {id}" ) 路径工作正常,我用Postman和浏览器测试过,但对于我的HTML客户端,我需要{id}部分 我的动态链接。 例如,我点击一些产品(假设我有一些带有某种产品的网页),浏览器会打开一个新窗口,所以我可以更新一个信息 关于那个产品。要进行更新,我需要该产品" id"在我的链接中,如下所示:http://www.something.com/ {id}

<form action="http://www.something.com/2" method="post">
        <input name="id" type="hidden">
        <input name="product_name">
        <input name="product_size">
        <input name="product_number">
        <input type="submit" value="Add">
</form>

在这个例子中,我只是硬编码了#39; {id}等于2,它有效! 但是,如何将http://www.something.com/ {id}&lt; - 此{id}部分设为动态(在我的index.html文件中)?

2 个答案:

答案 0 :(得分:1)

你需要做两件事

  1. 为表单添加ID和名称,例如
  2.   

    relatedItems.forEach(function(item,index) { if (item.get('slug') === itemModel.get('id')) { if (index === 0) { page.Prev = null; if(relatedItems.objectAt(index+1) ! = undefined) { page.Next = relatedItems.objectAt(index+1).get('slug'); }else{ page.Next == null; } } else if (index+1 === maxRecords) { if(relatedItems.objectAt(index-1) ! = undefined) { page.Prev = relatedItems.objectAt(index-1).get('slug'); }else{ page.Prev = null; } page.Next = null; } else { if(relatedItems.objectAt(index-1) ! = undefined) { page.Prev = relatedItems.objectAt(index-1).get('slug'); }else{ page.Prev = null; } if(relatedItems.objectAt(index+1) ! = undefined) { page.Next = relatedItems.objectAt(index+1).get('slug'); }else{ page.Next = null; } } }

    1. 编写一些JavaScript,动态地对正在执行的某些操作设置表单的操作,例如
    2. <form action="" method="post" name="my-form" id="my-form">

      但在我看来,我认为你最好直接使用JavaScript来发布帖子,而不是尝试更改表单操作。

答案 1 :(得分:1)

感谢您的回答,特别感谢@Toby提出的解决方案!如果有人在同一个问题上运行,我将分享我的最终解决方案:

...
<body onload="getId('id')">
    <div>
      <form action="http://www.something.com/{id}" method="post" id="productForm">
        <input name="id" type="hidden" id="id">
        <input name="product_name">
        <input name="product_size">
        <input name="product_number">
        <input type="submit" value="Add">
      </form>
    </div>              
    <script>
        var query = window.location.search.substring(1);
        var id = null;

        function getId (variable){
            var idArr = query.split("=");
            id = idArr[1];          
            document.getElementById("productForm").action="http://www.something.com/"+id;
            document.getElementById("id").value=id;
        }
    </script>       
</body>
...

我的带有REST路径的java类与此类似:

/**
 * to access:
 * http://www.something.com/{id}
 * @param id
 * @param product_name
 * @param product_size
 * @param product_number
 */
@Path("/{id}")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void tableUpdate(@FormParam("id") int id,@FormParam ("product_name") String name, @FormParam ("product_size") String size, @FormParam ("product_number") String number){
    ...
}
相关问题