2017-03-10 152 views
0

我有一个表单来插入用户。我使用POST方法和存储过程。将根据插入的数据自动调用ReturnStatusReturnMessageAjax:返回空值

我在插入数据之前遇到了一些错误,因为ajax返回值为null。但是当表格填写完整并提交工作时,并且设法显示成功操作的结果。

这是我的代码:

PHP

if(isset($_POST['submit'])) 
{ 

    $UserNm=$_POST["UserNm"]; 
    $UserId=$_POST["UserId"]; 
    $UserPwd=$_POST["UserPwd"]; 

    $stmt = odbc_exec(
     $conn, 
     "CALL UserInsert (
      '$UserNm', 
      '$UserId', 
      '$UserPwd',)" 
     ); 

    if (!$stmt) { 
     "Error : " . odbc_errormsg(); 
    } 

    if ($stmt) { 
     if (odbc_fetch_row($stmt)) { 
      $ReturnStatus=odbc_result($stmt,'ReturnStatus'); 
      $ReturnMessage=odbc_result($stmt,'ReturnMessage'); 
     } 

     if(isset($ReturnStatus) && $ReturnStatus==1) { 
      $ReturnMessage=odbc_result($stmt,'ReturnMessage'); 
     } 
    } 
} 

echo json_encode($ReturnMessage); 

?> 

脚本

<script> 
    $.ajax({ 
     url: "insert_sp.php", 
     dataType: "json", 
     success: function(data){ 
     alert(data.test); 
     } 
    }); 
</script> 

请帮助我。谢谢:)

+0

问题不清楚..........你可以用更好的explainination – Naincy

+0

编辑什么json_encode的'输出($ ReturnMessage)'? – hassan

+0

更新我的问题@ Naincy –

回答

1

检查,如果你的$ReturnMessage对象是UTF-8编码,因为json_encode只处理UTF-8编码的数据。 您可以http://php.net/manual/de/function.mb-detect-encoding.php测试编码,并与http://php.net/manual/de/function.utf8-encode.php

@see改变:http://php.net/manual/en/function.json-encode.php

所有字符串数据必须是UTF-8编码。

json_encode行前添加此行:

$ReturnMessage = utf8_encode ($ReturnMessage); 
+0

当我测试编码时,'$ ReturnMessage'返回'ASCII'。我对如何改变它们感到困惑。你能告诉我如何? @Paladin –

+0

@Mint:我编辑了我的帖子,看最后两行;) – Paladin

+0

谢谢:)。null消失了,被替换成''“'。然后,我改变了'if(isset($ _ POST ['submit']))'内的'json_encode'的位置,现在它们工作得很好。 –

1

你检查POST请求类型:

if(isset($_POST['submit'])) 

,而你的Ajax发送GET要求,了解更多关于如何POST使用AJAX和jQuery。

<script> 
    $.ajax({ 
     url: "insert_sp.php", 
     method: "POST", 
     data: {submit: 'true'}, 
     success: function(response) { 
     // while you are expecting a json response 
     // so you will need to decode it . 
     var data = JSON && JSON.parse(response) || $.parseJSON(response); 
     alert(data); 
     } 
    }); 
</script> 
+0

'null'值仍然存在。 @哈桑艾哈迈德。文档很混乱,但我会研究它。谢谢:) –

+0

更改此行'“错误:”。 odbc_errormsg();'为'echo“错误:”。 odbc_errormsg();';并检查是否有任何错误,并将此添加到ajax成功回调'alert(response);'并检查您的控制台。 – hassan

+0

没有错误。提交时会显示'$ ReturnMessage'替代null。但是当数据尚未提交时,我仍然无法在开始时清除“null”。 @HassanAhmed –