如何使用httpwebrequest在c#中获取网页(使用ajax / javascript的php)的最终响应

I am using c# windows application. I have a php file that uses javascript/ajax to validate login and return some data. When I execute this in browser it works fine, but when I send data from c# windows application via httpwebrequest it does not return the complete response. c# does not get response of after submitting browser data.

Kindly help me on this.

Below is my code

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript"> 
function Ajaxcall(){    
$.ajax({        
url: "XXXXXXXX",    // this url is a moodle url and validate user authentication then returns roleid
type: "POST",
async:true,     
data: {username: uname, password: pwd, TransactionId: TransactionId},
error: function (data)
{
document.write("Error");            
},
success: function(response)
{                       
var url = 'login.php';
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="RoleId" value="' + response + '" />'
'<input type="text" name="TransactionId" value="' + TransactionId + '" />'
'</form>');
$('body').append(form);
form.submit();
}
});
}
<?php 
//The below code will automatically execute after form submission
if (isset($_POST["RoleId"]))
{               
$NewRoleId =  $_POST["RoleId"];
$TransactionId = $_POST["TransactionId"];
$qry = "Update query is to update roleid in a table based on the transactionid";                
$result = mysql_query($qry);
if ($result)
echo "Updated successfully";
else
echo "Error in updating query";
exit();
}

'The below code runs when the page is loading and gets trnsactionid from the 'c#
if (isset($_POST['TransactionId']))
{               
    $qry = "select query returns username, password";
    echo "query:". $qry;
    $result = mysql_query($qry);

    if (mysql_num_rows($result) > 0)
    {
        $rows = mysql_fetch_array($result);                 
        echo "<script type='text/javascript'>var uname = '" . $rows["username"] . "', pwd = '" . $rows["password"] . "', TransactionId='" . $_POST['TransactionId'] . "';</script>";
       echo "<script language='JavaScript'>Ajaxcall(callbackfunction);  </script>";                 
    }
}
?>

C# code to post data:

String response = GetPost("XXXXX/Login.php", "TransactionId", "1")

public string GetPost(string Url, params string[] postdata)
{
    string result = string.Empty;
    string data = string.Empty;

    System.Text.ASCIIEncoding ascii = new ASCIIEncoding();

    if (postdata.Length % 2 != 0)
    {
        MessageBox.Show("Parameters must be even , \"user\" , \"value\" , ... etc", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        return string.Empty;
    }

    for (int i = 0; i < postdata.Length; i += 2)
    {
         data += string.Format("&{0}={1}", postdata[i], postdata[i + 1]);
    }

    data = data.Remove(0, 1);

    byte[] bytesarr = ascii.GetBytes(data);

    try
    {
        WebRequest request = WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = bytesarr.Length;

        System.IO.Stream streamwriter = request.GetRequestStream();
        streamwriter.Write(bytesarr, 0, bytesarr.Length);
        streamwriter.Close();

        WebResponse response = request.GetResponse();
        streamwriter = response.GetResponseStream();

        System.IO.StreamReader streamread = new  System.IO.StreamReader(streamwriter);
        result = streamread.ReadToEnd();

        streamread.Close();
    }
    catch (Exception ex)
    {
         MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

    return result;
}

1个回答



尝试添加 header()函数手动指定响应</ p>
</ div>

展开原文

原文

Try to add header() function to specify response manually

douweida2669
douweida2669 当我在c#中进行messageshow时,上面提到的3条评论正在作为回应。
5 年多之前 回复
donglan6967
donglan6967 <script type ='text / javascript'> var uname ='dynamic value',pwd ='dynamic value',',TransactionId ='dynamic value'; </ script> <script type ='text / javascript'> Ajaxcall( ); </ SCRIPT>
5 年多之前 回复
down00111
down00111 var form = $('<form action =“'+ url +'”method =“post”>'+'<input type =“text”name =“RoleId”value =“'+ response +'”/>' '<input type =“text”name =“TransactionId”value =“'+ TransactionId +'”/>''</ form>'); $( '主体')附加(形式)。 form.submit(); }}; } qeury:select query返回用户名,密码
5 年多之前 回复
duananyu9231
duananyu9231 <script src =“ajax.googleapis.com/ajax/libs/jquery/1.11.2/...> <script type =”text / javascript“> function Ajaxcall(){$ .ajax({url:”XXXXXXXX“,/ /此url是moodle url并验证用户身份验证然后返回roleid类型:“POST”,async:true,data:{username:uname,password:pwd,TransactionId:TransactionId},error:function(data){document.write (“错误”);},成功:函数(响应){var url ='Login.php';
5 年多之前 回复
duanleiliu7373
duanleiliu7373 我也做了这些改变。 我得到的答复如下
5 年多之前 回复
dongliugu8843
dongliugu8843 并且不推荐使用language属性,将其替换为'type'
5 年多之前 回复
dongmiao260399
dongmiao260399 是否有“<script language ='JavaScript'> Ajaxcall(); </ script>”作为回应?
5 年多之前 回复
dsj8000
dsj8000 先生,我修改了文件名并用完全url指定,我也改变了Ajaxcall的javascript调用(callbackfunction); 到Ajaxcall(); (我在PHP编码中犯了错误)。 但是,c#中的结果只是显示脚本,因为它与回显消息即qeury:
5 年多之前 回复
douchi0638
douchi0638 在处理请求的php代码中,url设置为'login.php',但在C#中它被称为“Login.php”。 在两种情况下也设置正确的完整URL(例如http:// localhost / login.php)
5 年多之前 回复
doujian7132
doujian7132 从c#发送数据后,我在php文件中收到“TransactionId”。 这里没有问题。 但是if((__ POST [“RoleId”])){}内写的代码没有达到。 当我从c #windows应用程序调用时,ajaxcall函数没有调用或者没有发生相同的页面重定向。 请告诉我如何解决这个问题。
5 年多之前 回复
dongque3797
dongque3797 如果我理解正确,您在UPDATE查询后没有响应。 因此,在exit()之前添加包含状态和内容类型的标头; 您是否在PHP代码中检查了从C#发送的POST请求的内容?
5 年多之前 回复
dousha1394
dousha1394 谢谢你的回复。 你能指出我在哪里添加header()以及需要在头文件中写入的内容。 谢谢
5 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐