PDA

View Full Version : مشكل در فراخواني تابع جاوااسكريپت در صفحه ديگر بويسله اجاكس



mojtabadj
دوشنبه 31 فروردین 1388, 22:38 عصر
من يك صفحه رو بوسيله اجاكس لود ميكنم كه تو اون صفحه يك تابع

جاوااسكريپت اجرا ميشه! در حالت عادي اجرا ميشه ولي زماني كه با

اجاكس اون صفحه رو لود ميكنم تابع جا وا اسكريپ رو اجرا نميكنه!

كد:


<script>
initRTE('<?= $content ?>', 'example.css');
</script>


ضمنا متغيير content$ تو صفحه مقدار ميگيره و جاي ديگه نميشه

لودش كرد

اگه ميشه راهنماييم كنيد

متشكر

امیـرحسین
دوشنبه 31 فروردین 1388, 23:14 عصر
من نمی دونم دقیقا کجا و کی ها، وقتی HTML رو با آژاکس لود می کنید، DOM tree بازخوانی (همون Refresh) نمیشه.
یعنی مثلا division جدید رو نمیشناسه. شاید مشکل همین باشه.

mojtabadj
سه شنبه 01 اردیبهشت 1388, 08:23 صبح
من نمی دونم دقیقا کجا و کی ها، وقتی HTML رو با آژاکس لود می کنید، DOM tree بازخوانی (همون Refresh) نمیشه.
یعنی مثلا division جدید رو نمیشناسه. شاید مشکل همین باشه.

خوب اگه مشكل اينه براي حل اين مشكل چه راه حل هايي پيشنهاد ميكنيد؟

اعظم
سه شنبه 01 اردیبهشت 1388, 09:20 صبح
مقادیر html , جاوا اسکریپتت رو با یک جدا کنند از هم جدا کن مثلا

html code %++% java code

بعد از فراخوانی صفحه توسط آژاکس دو باره دو بخش اچ تی ام ال و جاوا رو بر اساس جدا کننده ای که گذاشتی از هم جدا کن

بخش html رو در صفحه ست کن اما بخش جاوا رو توسط تابع eval در جاوا سکریپت اجرا کن

امیدوارم تونسته باشم خوب توضیح بدم

اعظم
سه شنبه 01 اردیبهشت 1388, 09:24 صبح
Myresponsetext1=Myresponsetext.split('%$$%');
document.getElementById(FieldName).innerHTML = Myresponsetext1[0]
eval(Myresponsetext1[1]);

اعظم
سه شنبه 01 اردیبهشت 1388, 09:26 صبح
فقط یک نکته این که

در صفحه php که کد html و java تولید میشه و بعد با یک جدا کننده از هم جدا می شنوند، کد جاوا نباید با تگ اسکریپت شروع بشه .

به عنوان مثال



< p> . . . . . </p>
%$$%
myjavafunction ();

mojtabadj
سه شنبه 01 اردیبهشت 1388, 11:53 صبح
فقط یک نکته این که

در صفحه php که کد html و java تولید میشه و بعد با یک جدا کننده از هم جدا می شنوند، کد جاوا نباید با تگ اسکریپت شروع بشه .

به عنوان مثال



< p> . . . . . </p>
%$$%
myjavafunction ();




اينكارو كردم ولي خطا ميده ممكن بگيد از كجاست

كد فراخوان اجاكس:



function SEP()
{
var Request=GetXmlHttpObject();
if (Request==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="pages.php";
url=url+"?page=0";
url=url+"&sid="+Math.random();
Request.onreadystatechange=function ()
{
if (Request.readyState==1)
{
if (document.getElementById('loading') != null) {
document.getElementById('loading').innerHTML =
" ... در حال لود شدن" + "<img src=\"image/loader.gif\" />";
}
}
if (Request.readyState==4)
{
if (document.getElementById('loading') != null) {
document.getElementById('loading').innerHTML = "";
}
var Myresponsetext1=Request.responseText.split('%$$%') ;
document.getElementById("main").innerHTML = Myresponsetext1[0]
eval(Myresponsetext1[1]);
document.getElementById("main").innerHTML = Myresponsetext1[2]
}
}
Request.open("GET",url,true);
Request.send(null);
}

<!--------------------------------------------------------------------------------------->
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}


كد صفحه pages.php :



<table width="100%" cellpadding="0" cellspacing="0" border="1">
<tr>
<td colspan="2">&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>صفحه مورد نظر را انتخاب كنيد :</td>
</tr>
<tr>
<td colspan="2" align="center">
<script src="js/richtext.js" type="text/javascript" language="javascript"></script>
<!-- Include the Free Rich Text Editor Variables Page -->
<script src="js/config.js" type="text/javascript" language="javascript"></script>
<?php
require('base.php');
conn();
$page=$_GET['page'];
$result=mysql_query("select * from pages where id='".$page."'");
if(!$result)
{
echo mysql_error();
exit();
}
$row=mysql_fetch_array($result);
function freeRTE_Preload($content) {
// Strip newline characters.
$content = str_replace(chr(10), " ", $content);
$content = str_replace(chr(13), " ", $content);
// Replace single quotes.
$content = str_replace(chr(145), chr(39), $content);
$content = str_replace(chr(146), chr(39), $content);
// Return the result.
return $content;
}
// Send the preloaded content to the function.
$content = freeRTE_Preload($row['content']);
?>
%$$%
initRTE(' $content ', 'example.css');
%$$%
</td>
</tr>
<tr>
<td colspan="2">&nbsp;</td>
</tr>
</table>

اعظم
سه شنبه 01 اردیبهشت 1388, 12:07 عصر
محدوده جاوا باید کاملا از کد اچ تی ام ال جدا باشه

یعنی اینطوری :





<table width="100%" cellpadding="0" cellspacing="0" border="1">
<tr>
<td colspan="2">&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>صفحه مورد نظر را انتخاب كنيد :</td>
</tr>
<tr>
<td colspan="2" align="center">
<script src="js/richtext.js" type="text/javascript" language="javascript"></script>
<!-- Include the Free Rich Text Editor Variables Page -->
<script src="js/config.js" type="text/javascript" language="javascript"></script>
<?php
require('base.php');
conn();
$page=$_GET['page'];
$result=mysql_query("select * from pages where id='".$page."'");
if(!$result)
{
echo mysql_error();
exit();
}
$row=mysql_fetch_array($result);
function freeRTE_Preload($content) {
// Strip newline characters.
$content = str_replace(chr(10), " ", $content);
$content = str_replace(chr(13), " ", $content);
// Replace single quotes.
$content = str_replace(chr(145), chr(39), $content);
$content = str_replace(chr(146), chr(39), $content);
// Return the result.
return $content;
}
// Send the preloaded content to the function.
$content = freeRTE_Preload($row['content']);
?>
</td>
</tr>
<tr>
<td colspan="2">&nbsp;</td>
</tr>
</table>

%$$%
echo("initRTE('". $content."', 'example.css');")

اعظم
سه شنبه 01 اردیبهشت 1388, 12:10 عصر
خطا رو باید بگی چیه
معمولا برای این خطا ها فقط از فایرفاکس و گزینه error console استفاده می کنم چون دقیق نمایش میده خطا رو


یه چیز دیگه این خط

initRTE(' $content ', 'example.css');
باید اینطوری بشه




echo("initRTE('". $content."', 'example.css');")

mojtabadj
چهارشنبه 02 اردیبهشت 1388, 08:19 صبح
خطا رو باید بگی چیه
معمولا برای این خطا ها فقط از فایرفاکس و گزینه error console استفاده می کنم چون دقیق نمایش میده خطا رو


یه چیز دیگه این خط

initRTE(' $content ', 'example.css');
باید اینطوری بشه




echo("initRTE('". $content."', 'example.css');")


با تشكر از شما دوست عزيز

خطاش اينه:


initRTE is not defined

اعظم
چهارشنبه 02 اردیبهشت 1388, 09:07 صبح
احتمالا یک جاوا سکریپت خارجی داری که در صفحه php لود میشه ، اگر اینطور هستش این فایل جاوا اسکریپت خارجی رو در صفحه اصلی ( که از طریق آجاکس فایل php در ان لود میشه ) قرار بده .

mojtabadj
پنج شنبه 03 اردیبهشت 1388, 08:47 صبح
احتمالا یک جاوا سکریپت خارجی داری که در صفحه php لود میشه ، اگر اینطور هستش این فایل جاوا اسکریپت خارجی رو در صفحه اصلی ( که از طریق آجاکس فایل php در ان لود میشه ) قرار بده .

با تشکر از شما دوست عزیز

در واقع من با این تابع دارم یک ادیتور لود میکنم این راهی که گفتید جواب داد ولی زمانی که

ادیتور لود میشه کد های قبلی رو نادیده میگیره و فقط ادیتور رو لود میکنه

تنها مرورگری که خوب لود میکنه safari هستش باید چی کار کنم؟

اعظم
پنج شنبه 03 اردیبهشت 1388, 09:57 صبح
راستش این مشکل رو تا از نزدیک نبینم نمی تونم نظری بدم ( هنوز نتونستم دقیقا بفهمم چه اتفاقی میافته ) اما من به همین روش fck editor و yahoo editor رو استفاده کردم و مشکلی هم نداشتم .

mojtabadj
جمعه 04 اردیبهشت 1388, 18:32 عصر
با سلام به دوست عزيز

ببخشيد ميتونيد يك نمونه كار لود fck اديتور با اجاكس رو برام بذاريد؟

با تشكر

اعظم
شنبه 05 اردیبهشت 1388, 10:19 صبح
یک نمونه گذاشتم که در ie8 ، Firefox , chrom تستش کردم

من نتونستم فایل زیپ رو ضمیمه کنم بنابراین سورس فیلها رو اینجا میزارم

index.php


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>


<script type="text/javascript" src="fckeditor/fckeditor.js"></script>
<script type="text/javascript">

function FCKeditor_OnComplete( editorInstance )
{
editorInstance.Events.AttachEvent( 'OnBlur' , FCKeditor_OnBlur ) ;
editorInstance.Events.AttachEvent( 'OnFocus', FCKeditor_OnFocus ) ;
}

function FCKeditor_OnBlur( editorInstance )
{
editorInstance.ToolbarSet.Collapse() ;
}

function FCKeditor_OnFocus( editorInstance )
{
editorInstance.ToolbarSet.Expand() ;
}

function myeditor(Editor_name)
{

var sBasePath ='fckeditor/'

var oFCKeditor = new FCKeditor( Editor_name) ;

oFCKeditor.Config['ToolbarStartExpanded'] = false ;

oFCKeditor.BasePath = sBasePath ;
//oFCKeditor.ToolbarSet = 'DiamondPanel' ;
oFCKeditor.Value = '';
oFCKeditor.Width=550;

oFCKeditor.ReplaceTextarea() ;

return oFCKeditor;
}


//************************************************** ****
function MakeConnection()
{
var httpRequest;
if (window.XMLHttpRequest) // Mozilla, Safari, Opera
{
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType)
{
httpRequest.overrideMimeType('text/html');
}
}
else if (window.ActiveXObject) // IE
{
try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e)
{
try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
}
}
if (!httpRequest)
{
alert('ERROR : Cannot create an XMLHTTP instance!');
return false;
}
return httpRequest;
}



//************************************************** *****
//************************************************** *****
// Set Content
//************************************************** *****
//************************************************** *****
function Set_Content(Proccess_Type,Page_Address,Page_Addres s_Query,SynType,Content_Id)
{
var HttpConn = MakeConnection();
if (Proccess_Type=='get')
{
HttpConn.open(Proccess_Type, Page_Address+'?'+Page_Address_Query,SynType);
}
else
{
HttpConn.open(Proccess_Type, Page_Address,SynType);
}
HttpConn.onreadystatechange = function ()
{

if ((HttpConn.readyState == 4)&&(HttpConn.status == 200))
{

var MyResponse1=HttpConn.responseText.split('$##$');
document.getElementById(Content_Id).innerHTML=MyRe sponse1[0];
eval(MyResponse1[1]);
}
};

if (Proccess_Type=='get')
{
HttpConn.send(null);
}
else
{
HttpConn.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
HttpConn.send(Page_Address_Query);
}
}


</script>


</head>

<body>
<table width="700" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="700" height="50" dir="rtl" align="right"><h1>لود کردن ادیتور از طریق آجاکس</h1></td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>
<tr>
<td id="Content_TD">&nbsp;</td>
</tr>
<tr>
<td align="center" valign="middle"><input type="button" name="S1" id="S1" value="Load Editor" onclick="Set_Content('post','01.php','',true,'Content_TD')" /></td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>
<tr>
<td height="50" bgcolor="#006666">&nbsp;</td>
</tr>
</table>
</body>
</html>





01.php




<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr height="15">
<td width="25" height="15"></td>
<td height="15"><form action="<?php echo($PHP_SELF)?>" method="post" id="az_form" name="az_form" enctype="multipart/form-data" onsubmit="return set_add_value()" >
<div align="center">
<table width="100%" border="0" cellspacing="3" cellpadding="0">
<tr>
<td align="left" id="err_box" name="err_box"></td>
</tr>
<tr>
<td align="center"><br></td>
</tr>
<tr>
<td align="right"><table border="0" cellspacing="0" cellpadding="0" align="right">
<tr>
<td align="right" dir="ltr">&nbsp;</td>
<td align="right" dir="ltr"><textarea name="Item_Title" id="Item_Title" rows="3" cols="70" tabindex="1"></textarea></td>
<td class="text" id="pid1" name="pid1" align="right" dir="ltr" width="120">* عنوان مطلب :</td>
</tr>
</table></td>
</tr>
<tr>
<td align="right"><br></td>
</tr>
<tr>
<td align="right"><table border="0" cellspacing="0" cellpadding="0" align="right">
<tr>
<td align="right" dir="rtl"><textarea name="Item_Text" id="Item_Text" rows="15" cols="88" tabindex="3"></textarea></td>
<td class="text" id="IT" name="IT" align="right" dir="ltr" width="120">* متن كامل :</td>
</tr>
</table></td>
</tr>
<tr>
<td><br></td>
</tr>
<tr>
<td align="center"><input type="hidden" name="mode" id="mode" value="add">
<input class="submit" value="ثبت اطلاعات" type="submit" name="s3" id="s3" tabindex="4"></td>
</tr>
<tr>
<td align="center"></td>
</tr>
<tr>
<td align="right">[ <a href="list.php">بازگشت به فهرست مطالب</a> ]</td>
</tr>
<tr>
<td align="center"><br></td>
</tr>
</table>
</div>
</form></td>
<td width="25" height="15"></td>
</tr>
</table>$##$myeditor('Item_Text');


فقط آدرس اسکریپت های fckeditor رو در فایل index.php باید تصحیح کنید

mojtabadj
شنبه 05 اردیبهشت 1388, 12:14 عصر
دستت درد نكنه خيلي با كدت حال كردم خيلي خيلي ممنون

حالا دارم تنظيمش ميكنم كه اطلاعتو از پايگاه داه بخونه و بنويسه!

راستي يه چيزي، fck اديتورم تويه ie فارسي نشون ميده ولي تو مرورگرهاي ديگه اينطور نيست

بايد چيكار كنم كه تو بقيه هم فارسي نشون بده؟

با تشكر از شما دوست عزيز

mojtabadj
شنبه 05 اردیبهشت 1388, 21:30 عصر
سلام

من در مورد خوندن اطلاعات و نشان دادن آن در fck مشكلي ندارم ولي براي ذخيره آن نميخوام از submit

استفاده كنم براي همين يك button تعريف كردم ولي مقداري رو كه از textarea ميگيرم مقداري نيست كه

پس از تغييرات بوجود اومده براي اينكار تو رويداد onclick در دكمه مورد نظر اين كد رو گذاشتم



$msg="page=".$page."&q=";

<input type="button" value="ثبت اطلاعات"
onclick="Set_Content('get','pages.php','<?= $msg ?>'+document.getElementById('Item_Text').value,true, 'main')"
name="s1" id="s1" class="input"/>


چه راه حلي پيشنهاد ميكنيد؟

با تشكر

__ziXet__
شنبه 05 اردیبهشت 1388, 22:45 عصر
اینو ببین:http://www.webdeveloper.com/forum/showthread.php?t=138830
بعد از لود شدن صفحه با DOM جاوااسکریپت رو پیدا میکنه بعد eval میکنه

mojtabadj
یک شنبه 06 اردیبهشت 1388, 11:27 صبح
سلام

دوستان عزيز راه حلي نداريد كه بدون post ،اطلاعات اديتور رو بگيريم و با اجاكس ذخيره كنيم؟

تشكر

اعظم
یک شنبه 06 اردیبهشت 1388, 11:55 صبح
مقدار fck editor در جاوا اسکریپت به شکل زیر گرفته می شود :



var field = FCKeditorAPI.GetInstance('Item_Text');
;(var value1 = field.GetHTML(false

mojtabadj
یک شنبه 06 اردیبهشت 1388, 13:10 عصر
مقدار fck editor در جاوا اسکریپت به شکل زیر گرفته می شود :



var field = FCKeditorAPI.GetInstance('Item_Text');
;(var value1 = field.GetHTML(false




خدا عمرت بده دستت درد نكنه هيچ كي جواب نميداد:ناراحت:

باز هم تشكر

mojtabadj
یک شنبه 06 اردیبهشت 1388, 17:55 عصر
سلام به تمام دوستان

همون كه دوستمون گفت مقدار اديتور رو با اين تابع گرفتم


function ValueOfFCK()
{
var field = FCKeditorAPI.GetInstance('Item_Text');
var value = field.GetHTML(false);
return value;
}


بعدش تو رويداد دكمه اي كه تعريف كرده بودم اين تابع را صدا زدم


$msg="page=".$page."&q=";

<input type="button" value="ثبت اطلاعات"
onclick="Set_Content('POST','pages.php','<?= $msg ?>'+ValueOfFCK(),true,'main')"
name="s1" id="s1" class="input"/>

مقدار يه درستي گرفته ميشه ولي يه مشكل وجود داره اونم زماني هست كه مقدار تابع ()ValueOfFCK در

متغيير q ريخته ميشه چون محدوده url محدود هست تمام اطلاعت ارسال نميشن چه راه حلي براي ارسال

اطلاعت پيشنهاد ميديد؟

با تشكر

اعظم
یک شنبه 06 اردیبهشت 1388, 18:28 عصر
HttpConn.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

در واقع دستور بالا مشخص می کنه که نوع فرم application/x-www-form-urlencoded که برای ارسال داده های بزرگ استفاده نمیشه . برای این کار باید نوع فرم رو multipart/form-data تنظیم کنی . من اینکار رو در آجاکس نکردمو نمی دونم در این حالت چطور باید پکیج داده رو ارسال کرد اما شاید این کمکت کنه :




application/x-www-form-urlencoded

This is the default content type. Forms submitted with this content type must be encoded as follows:

Control names and values are escaped. Space characters are replaced by `+', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by `%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., `%0D%0A').
The control names/values are listed in the order they appear in the document. The name is separated from the value by `=' and name/value pairs are separated from each other by `&'.





multipart/form-data


Note. Please consult [RFC2388] for additional information about file uploads, including backwards compatibility issues, the relationship between "multipart/form-data" and other content types, performance issues, etc.

Please consult the appendix for information about security issues for forms.

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

The content "multipart/form-data" follows the rules of all multipart MIME data streams as outlined in [RFC2045]. The definition of "multipart/form-data" is available at the [IANA] registry.

A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data; how this is done lies outside the scope of this specification.

As with all multipart MIME types, each part has an optional "Content-Type" header that defaults to "text/plain". User agents should supply the "Content-Type" header, accompanied by a "charset" parameter.

Each part is expected to contain:

a "Content-Disposition" header whose value is "form-data".
a name attribute specifying the control name of the corresponding control. Control names originally encoded in non-ASCII character sets may be encoded using the method outlined in [RFC2045].
Thus, for example, for a control named "mycontrol", the corresponding part would be specified:

Content-Disposition: form-data; name="mycontrol"
As with all MIME transmissions, "CR LF" (i.e., `%0D%0A') is used to separate lines of data.

Each part may be encoded and the "Content-Transfer-Encoding" header supplied if the value of that part does not conform to the default (7BIT) encoding (see [RFC2045], section 6)

If the contents of a file are submitted with a form, the file input should be identified by the appropriate content type (e.g., "application/octet-stream"). If multiple files are to be returned as the result of a single form entry, they should be returned as "multipart/mixed" embedded within the "multipart/form-data".

The user agent should attempt to supply a file name for each submitted file. The file name may be specified with the "filename" parameter of the 'Content-Disposition: form-data' header, or, in the case of multiple files, in a 'Content-Disposition: file' header of the subpart. If the file name of the client's operating system is not in US-ASCII, the file name might be approximated or encoded using the method of [RFC2045]. This is convenient for those cases where, for example, the uploaded files might contain references to each other (e.g., a TeX file and its ".sty" auxiliary style description).

The following example illustrates "multipart/form-data" encoding. Suppose we have the following form:

<FORM action="http://server.com/cgi/handle"
enctype="multipart/form-data"
method="post">
<P>
What is your name? <INPUT type="text" name="submit-name"><BR>
What files are you sending? <INPUT type="file" name="files"><BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</FORM>
If the user enters "Larry" in the text input, and selects the text file "file1.txt", the user agent might send back the following data:

Content-Type: multipart/form-data; boundary=AaB03x

--AaB03x
Content-Disposition: form-data; name="submit-name"

Larry
--AaB03x
Content-Disposition: form-data; name="files"; filename="file1.txt"
Content-Type: text/plain

... contents of file1.txt ...
--AaB03x--
If the user selected a second (image) file "file2.gif", the user agent might construct the parts as follows:

Content-Type: multipart/form-data; boundary=AaB03x

--AaB03x
Content-Disposition: form-data; name="submit-name"

Larry
--AaB03x
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=BbC04y

--BbC04y
Content-Disposition: file; filename="file1.txt"
Content-Type: text/plain

... contents of file1.txt ...
--BbC04y
Content-Disposition: file; filename="file2.gif"
Content-Type: image/gif
Content-Transfer-Encoding: binary

...contents of file2.gif...
--BbC04y--
--AaB03x--

mojtabadj
سه شنبه 08 اردیبهشت 1388, 08:05 صبح
فكر كنم بايد اين طور باشه ولي نميشه url فرستاد!


http_request.setRequestHeader("Content-type", "multipart/form-data");


من يه كد upload با اجاكس ديدم كه به صورت بالا استفاده كرده بود شما هم نگاه كنيد ببنيد فكري

به نظرتون ميرسه يا نه!

صفحه index.php



<html>
<body>
<script>
var url = "post.php";
var binary;
var filename;
var mytext;

function upload() {
filename = document.getElementById('myfile').value;
mytext = document.getElementById('mytext').value;
document.getElementById('ajaxbutton').disabled = true;

// request local file read permission
/*try {
netscape.security.PrivilegeManager.enablePrivilege ("UniversalXPConnect");
} catch (e) {
alert("Permission to read file was denied.");
}*/

// open the local file
var file = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile );
file.initWithPath( filename );
stream = Components.classes["@mozilla.org/network/file-input-stream;1"]
.createInstance(Components.interfaces.nsIFileInput Stream);
stream.init(file, 0x01, 00004, null);
var bstream = Components.classes["@mozilla.org/network/buffered-input-stream;1"]
.getService();
bstream.QueryInterface(Components.interfaces.nsIBu fferedInputStream);
bstream.init(stream, 1000);
bstream.QueryInterface(Components.interfaces.nsIIn putStream);
binary = Components.classes["@mozilla.org/binaryinputstream;1"]
.createInstance(Components.interfaces.nsIBinaryInp utStream);
binary.setInputStream (stream);

// start AJAX file upload in 1 second
window.setTimeout("ajax_upload()", 1000);
}

function ajax_upload() {
// request more permissions
/*try {
netscape.security.PrivilegeManager.enablePrivilege ("UniversalXPConnect");
} catch (e) {
alert("Permission to read file was denied.");
}*/

http_request = false;
http_request = new XMLHttpRequest();
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}

// prepare the MIME POST data
var boundaryString = 'capitano';
var boundary = '--' + boundaryString;
var requestbody = boundary + '\n'
+ 'Content-Disposition: form-data; name="mytext"' + '\n'
+ '\n'
+ mytext + '\n'
+ '\n'
+ boundary + '\n'
+ 'Content-Disposition: form-data; name="myfile"; filename="'
+ filename + '"' + '\n'
+ 'Content-Type: application/octet-stream' + '\n'
+ '\n'
+ escape(binary.readBytes(binary.available()))
+ '\n'
+ boundary;

document.getElementById('sizespan').innerHTML =
"requestbody.length=" + requestbody.length;

// do the AJAX request
http_request.onreadystatechange = requestdone;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "multipart/form-data; \boundary=\"" +boundaryString + "\"");
http_request.setRequestHeader("Connection", "close");
http_request.setRequestHeader("Content-length", requestbody.length);
http_request.send(requestbody);

}

function requestdone() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
result = http_request.responseText;
document.getElementById('myspan').innerHTML = result;
} else {
alert('There was a problem with the request.');
}
document.getElementById('ajaxbutton').disabled = false;
}
}

</script>

<form>
Text: <input type="text" id="mytext" name="mytext" size="40">
<br>
File: <input type="file" id="myfile" name="datafile" size="40"><br>
<input type="button" id="ajaxbutton" value="AJAX IT" onclick="upload();">
</form>

<div id="sizespan"></div>
<hr>
<div id="myspan"></div>

</body>
</html>


صفحه post.php



<?
print_r($_FILES);
?>
<hr>
<?
print_r($_POST);

$fpath = "/tmp/";

// move (actually just rename) the temporary file to the real name
move_uploaded_file ( $_FILES{myfile}{tmp_name}, $fpath.$_FILES{myfile}{name} );

// convert the uploaded file back to binary

// javascript "escape" does not encode the plus sign "+", but "urldecode"
// in PHP make a space " ". So replace any "+" in the file with %2B first

$filename = $fpath.$_FILES{myfile}{name};
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

$contents = preg_replace("/\+/", "%2B", $contents);

$handle = fopen($filename, "w");
fwrite($handle, urldecode($contents));
fclose($handle);

?>


با تشكر

اعظم
سه شنبه 08 اردیبهشت 1388, 18:58 عصر
یک تابع در کلاس snoopy هست که این کار رو میکنه این تابع باید به جاوا اسکریپت برگردونده شه ( که متاسفانه من نمی تونم الان روش وقت بزارم و تبدیلش کنم ) اما شباهتی به کدی که گذاشتی هم داره
کد php



function _prepare_post_body($formvars, $formfiles)
{
settype($formvars, "array");
settype($formfiles, "array");
$postdata = '';

if (count($formvars) == 0 && count($formfiles) == 0)
return;

switch ($this->_submit_type) {
case "application/x-www-form-urlencoded":
reset($formvars);
while(list($key,$val) = each($formvars)) {
if (is_array($val) || is_object($val)) {
while (list($cur_key, $cur_val) = each($val)) {
$postdata .= urlencode($key)."[]=".urlencode($cur_val)."&";
}
} else
$postdata .= urlencode($key)."=".urlencode($val)."&";
}
break;

case "multipart/form-data":
$this->_mime_boundary = "Snoopy".md5(uniqid(microtime()));

reset($formvars);
while(list($key,$val) = each($formvars)) {
if (is_array($val) || is_object($val)) {
while (list($cur_key, $cur_val) = each($val)) {
$postdata .= "--".$this->_mime_boundary."\r\n";
$postdata .= "Content-Disposition: form-data; name=\"$key\[\]\"\r\n\r\n";
$postdata .= "$cur_val\r\n";
}
} else {
$postdata .= "--".$this->_mime_boundary."\r\n";
$postdata .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n";
$postdata .= "$val\r\n";
}
}

reset($formfiles);
while (list($field_name, $file_names) = each($formfiles)) {
settype($file_names, "array");
while (list(, $file_name) = each($file_names)) {
if (!is_readable($file_name)) continue;

$fp = fopen($file_name, "r");
$file_content = fread($fp, filesize($file_name));
fclose($fp);
$base_name = basename($file_name);

$postdata .= "--".$this->_mime_boundary."\r\n";
$postdata .= "Content-Disposition: form-data; name=\"$field_name\"; filename=\"$base_name\"\r\n\r\n";
$postdata .= "$file_content\r\n";
}
}
$postdata .= "--".$this->_mime_boundary."--\r\n";
break;
}

return $postdata;
}




و این بخش از کد شما :



// prepare the MIME POST data
var boundaryString = 'capitano';
var boundary = '--' + boundaryString;
var requestbody = boundary + '\n'
+ 'Content-Disposition: form-data; name="mytext"' + '\n'
+ '\n'
+ mytext + '\n'
+ '\n'
+ boundary + '\n'
+ 'Content-Disposition: form-data; name="myfile"; filename="'
+ filename + '"' + '\n'
+ 'Content-Type: application/octet-stream' + '\n'
+ '\n'
+ escape(binary.readBytes(binary.available()))
+ '\n'
+ boundary;

اعظم
سه شنبه 08 اردیبهشت 1388, 19:16 عصر
اگر نخواهید فایلی آپلود کنید از این قسمت کد صرف نظر کنید




reset($formfiles);
while (list($field_name, $file_names) = each($formfiles)) {
settype($file_names, "array");
while (list(, $file_name) = each($file_names)) {
if (!is_readable($file_name)) continue;

$fp = fopen($file_name, "r");
$file_content = fread($fp, filesize($file_name));
fclose($fp);
$base_name = basename($file_name);

$postdata .= "--".$this->_mime_boundary."\r\n";
$postdata .= "Content-Disposition: form-data; name=\"$field_name\"; filename=\"$base_name\"\r\n\r\n";
$postdata .= "$file_content\r\n";
}
}

mojtabadj
پنج شنبه 10 اردیبهشت 1388, 08:44 صبح
با سلام به دوستان عزیز

باز هم تو اصل موضوع تغییری ایجاد نشد بازم نمیشه url بزرگ فرستاد:ناراحت:

mojtabadj
شنبه 12 اردیبهشت 1388, 08:42 صبح
كسي نيست تا راهنمايي كنه؟