您好我是Android新手,特别是JSon。我正在尝试将我的Android应用程序与连接到WAMP的php文件连接。 但我得到“字符串无法转换为JSONObject。 这是我的PHP代码:
if(isset($_POST['check'])){
$name = $_POST['txtuser'];
$pass = $_POST['txtpass'];
$sql = "Select * from tbluser where username = '".$name."' and password = '".$pass."'";
$query = mysql_query($sql, $conn);
$result = mysql_fetch_array($query);
$flag['code'] = 0;
if(mysql_num_rows($query) > 0){
$flag['code'] = 1;
echo '<script type="text/javascript">alert("Hello");</script>';
json_encode($flag);
}
这是我的Android代码:
public void select()
{
ArrayList<NameValuePair> userpass = new ArrayList<NameValuePair>();
String x = txtname.getText().toString();
String y = txtpass.getText().toString();
userpass.add(new BasicNameValuePair("user", x));
userpass.add(new BasicNameValuePair("pass",y));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.254.100/adphptest/index.php");
httppost.setEntity(new UrlEncodedFormEntity(userpass));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(json);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "User verified!",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Invalid!",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
答案 0 :(得分:0)
转到c:\ wamp \ alias \ phpmyadmin.conf并更改此
<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Directory>
到
<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Allow from all
</Directory>
答案 1 :(得分:0)
除非我错过了一些显而易见的问题,否则在输出json对象之前你的php文件会用这行回显非json字符串
echo '<script type="text/javascript">alert("Hello");</script>';
这是你的Android json解析代码首先看到失败的原因。