我有函数showuser()
,它在表单提交事件上发布变量sent
。
我在同一个函数中获得了更多变量,并希望使用sent
发布它,但是它们没有在另一个页面上收到。
这是我的代码,我的错误是什么?
function showUser(form, e) {
e.preventDefault();
e.returnValue=false;
var xmlhttp;
var sent = form.elements['sent'].value;
var sent2 = form.elements['sent2'].value; // sent2 is the name of one of <div> in the form where sent is there. But getting error : "TypeError: form.elements.sent2 is undefined"
var divElements = document.getElementById('d1').innerHTML;
var text1 = document.getElementById('previewUrl').innerText || document.getElementById('previewUrl').textContent;
var text2 = document.getElementById('previewTitle').innerText || document.getElementById('previewTitle').textContent;
var text3 = document.getElementById('previewDescription').innerText || document.getElementById('previewDescription').textContent;
// I want to post text1,2,3 along with sent to another page where sent get received
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send('sent=' + sent + 'text1=' + text1 + 'text2=' + text2 + 'text3=' + text3);
}
数据来自以下形式:
<form>
<input type="text" id="text" name="sent" contenteditable="true" style=" text-align: left; height: 30px; width:512px; " placeholder="Enter URL ..."/></input>
<div id="d1" height="40" width="60" name="sent2" style=" border:1px solid black; z-index: 1; left: 950px; top:80px; position: absolute; margin-top: 0px" placeholder="Preview title" >
</div>
<div id="d2" height="40" style="border:1px solid black; z-index: 1; left: 950px; top:100px; position: absolute; margin-top: 0px; min-width:60; overflow:auto" placeholder="Preview Url">
</div>
<div id="d3" height="80" border="1" style="border:1px solid black; z-index: 1; left: 950px; top:140px; position: absolute; margin-top: 0px" placeholder="Preview Desciption">
</div>
//Some other content
</form>
我还尝试使用以下方法获取表单提交事件的内容值:
var sent2 = form.elements['sent2'].value; //sent2 name of <div id="d1">
但没有运气
答案 0 :(得分:1)
您的键/值字符串缺少用于分隔变量的&
字符。您还应该通过encodeURIComponent()
运行它们,以便对特殊字符进行URL编码,并且不会破坏格式。
sent = encodeURIComponent(sent);
text1 = encodeURIComponent(text1);
text2 = encodeURIComponent(text2);
text3 = encodeURIComponent(text3);
xmlhttp.send('sent=' + sent + '&text1=' + text1 + '&text2=' + text2 + '&text3=' + text3);
// ^ here ^ here ^ here