Javascript array for AJAX POST send

血红的双手。 提交于 2019-12-08 06:56:52

问题


Here is the deal... I need to make an AJAX save script. I have a whole system built on php and every action needs a refresh... I'm trying to minimize the refresh count by using AJAX ... I can't seem to find a way how to send a WYSIWYG editor output without loss to the PHP script...

  if (window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
}
else{
    xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}
function save(){
    xmlhttp.open('POST','action.php',true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", document.getElementById('output').value.length);
    xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.send(document.getElementById('output').value);
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status==200){
            $('#ajaxresult').css('opacity', 0.1);
            $('#ajaxresult').stopAll().pause(1000).fadeTo(400,1);
            $('#ajaxresult').stopAll().pause(3000).fadeTo(400,0, function(){$(this).hide();});
            document.getElementById('ajaxresult').innerHTML=xmlhttp.responseText;
        }
    }
}

While this script works fine I can't seem to find the way what kind of array to give the send option... what is the syntax or is there something I don't know?

BTW I'm a beginner in JS...


回答1:


I'd look into using jQuery and it's Ajax library:

http://api.jquery.com/jQuery.ajax/

Instead of doing all that you'd simply do:

$.post({url: 'action.php',data: output,success: function() { /* do something here */ }});



回答2:


create custom parameter in the javascript code like below:

   var jspNameParam = "content="+escape(document.getElementById('output').value);
    function myFunction() {
        if (xmlhttp) {
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4) {
                /*  want to accsess some data written from action.php */
                }   
            };          
            xmlhttp.open("POST", "action.php", true);   
            xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xmlhttp.send(jspNameParam);
        }
    }

Now in action.php you will get whole content with the parameter name content.



来源:https://stackoverflow.com/questions/5330957/javascript-array-for-ajax-post-send

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!