I have a html page that requires creation of forms literally like:
<form action="/tasks/<%= allTasks.e[0].id %>/delete" method="POST">
<button class="deleteTask">Delete</button>
</form>
But when in a javascript file using jQuery and I do
$(function(){
let myform=String("<form action='/tasks/<%= allTasks.e[0].id%>/delete' method='POST'>
<button>DELETE</button></form>");
$('span').each(function(){$(this).append(myform)});
})
It will show Cannot POST /tasks/%3C%25=%20allTasks.e[0].id%20%25%253E/delete
The reason is the special characters %,<> got replaced with those numbers. How can I prevent this from happening?
Thanks!
The reason of POST failure is NOT because of the special characters %
, <>
got replaced, but because the server side template stuff ( <%= %>
) is not replaced.
You need to replace <%= allTasks.e[0].id%>
in the myForm
String to use the real task id. It means your server side technology need to handle JavaScript file content, or the JavaScript code with <%= allTasks.e[0].id%>
stuff should be moved to HTML template file.
The HTTP POST request should look like:
POST /tasks/33989/delete
not
POST /tasks/<%= allTasks.e[0].id%>/delete
BTW, to make the request more RESTful, it is better to use HTTP method DELETE
.
UPDATE: If javascript file needs to get task id passed from backend, there is a simple way:
<script>
element. In the above script element, store the task id data in the global window object.
window.taskId = '<%= allTasks.e[0].id%>';
In this way, when the HTML is assembled in backend, the above code would be converted to:
window.taskId = '77878';
When jQuery need to send Ajax request, it can extract the task id from window
object:
let actionURL = '/tasks/' + window.taskId + '/delete';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.