Reputation: 1
I wonder how to add string at the end of the url in Js. The url must to be available in a variable, so I can request it. And I get the inputs from a form.
example:
http://localhost:3000/items/ -> http://localhost:3000/items/55ef09351ee9ce3c272ef8e7
Here's my code:
var link = "http://localhost:3000" + input._id.value
link = link.replace('?_id=', '');
var xhr = new XMLHttpRequest();
xhr.open("DELETE", link, false);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
With this code I get localhost:3000/items/?_id=55ef09351ee9ce3c272ef8e7 How can I make it without the ?_id= ?
code from program
<form onsubmit="submit" action="http://localhost:3000/items/" method="delete" name="del_stuff">
_id:<br>
<input type="text" name="_id">
<br>
<br>
<input type="submit" value="Submit">
</form>
</form>
<div id="output"></div>
<script type="text/javascript">
var form = function submit(e) {
// stop the regular form submission
e.preventDefault();
var link = "http://localhost:3000/items" + encodeURIComponent(input._id.value)
link = link.replace('?_id=', '');
// collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
}
// construct an HTTP request
alert("http request");
var xhr = new XMLHttpRequest();
xhr.open("DELETE", link, false);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
// send the collected data as JSON
xhr.send(JSON.stringify(data));
xhr.onloadend = function () {
// done
};
};
</script>
Thx
Upvotes: 0
Views: 241
Reputation: 1213
With this code I get localhost:3000/items/?_id=55ef09351ee9ce3c272ef8e7 How can I make it without the ?_id= ?
Please check out this fiddle, it worked fine!
var link = "http://localhost:3000/?_id=55ef09351ee9ce3c272ef8e7"
link = link.replace('?_id=', '');
alert(link);
Upvotes: 0
Reputation: 2560
Normally you have to modify the .htaccess file. This is how you would define a rule to remove question mark from a URL,
RewriteCond %{QUERY_STRING} ^(.+)$
RewriteRule ^(.*)$ $1%1? [R,L]
Upvotes: 0
Reputation: 1171
I wonder how to add string at the end of the url in Js. The url must to be available in a variable, so I can request it.
location.href += input._id.value;
Now how you want to format the url is upto you.
Upvotes: 0
Reputation: 3084
use the encodeURIComponent
function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
var link = "http://localhost:3000" + encodeURIComponent(input._id.value)
Upvotes: 2